我不确定我是否应该开始一个新线程,但由于编辑我以前的问题会涉及大量重新排列代码,我认为一个新线程是最好的。
template <class T>
class node {
public:
T value;
node<T> *next;
node<T> *previous;
};
template <class T>
class my_list {
public:
node<T> *first;
node<T> *last;
my_list(){
first = NULL;
last = NULL;
}
~my_list(){
}
void push_back(T val);
void push_front(T val);
void pop_back();
void pop_front();
T front();
T back();
};
以上是班级布局。下面是 pop_back() 方法,它应该删除列表中的最后一个节点。我无法让它工作。它运行但似乎没有重新分配最后一个节点,因为当我调用 T back() 函数时它返回一个随机值。
template <class T>
void my_list<T>::pop_back(){
node<T> oldlast = *this->last;
node<T> newlast = *oldlast.previous;
cout << newlast.value << endl;
newlast.next = NULL;
this->last = this->last->previous;
}
template <class T>
void my_list<T>::push_back(T val){
if (this->first == NULL) {
node<T> newnode;
newnode.value = val;
newnode.next = NULL;
newnode.previous = NULL;
this->first = &newnode;
this->last = &newnode;
} else {
node<T> current = *this->last;
node<T> newnode;
newnode.value = val;
newnode.previous = ¤t;
newnode.next = NULL;
current.next = &newnode;
this->last = &newnode;
}
}
template <class T>
void my_list<T>::push_front(T val){
if (this->first == NULL) {
node<T> newnode;
newnode.value = val;
newnode.next = NULL;
newnode.previous = NULL;
this->first = &newnode;
this->last = &newnode;
} else {
node<T> current = *this->first;
node<T> newnode;
newnode.value = val;
newnode.previous = NULL;
newnode.next = ¤t;
current.previous = &newnode;
this->first = &newnode;
}
}