template <class T>
bool LinkedList<T>::remove(const T object){
Node<T> *cur = head;
while(cur->next != NULL){
if(cur->next->value == object){
Node<T>* temp = cur->next->next;
delete cur->next;
cur->next = temp;
s--;
return true;
}
cur = cur->next;
}
return false;
}
我在分配后删除对象。当我打印出值时,节点似乎已损坏。这是从链表中删除项目的最佳方法吗?
节点析构函数只是"删除下一个"。
哎呀。如果每个节点都删除其析构函数中的下一个节点,则会导致从该点开始的整个列表被删除!
Node<T>* temp = cur->next->next; // the node temp points to is clearly after cur
delete cur->next; // deletes everything after cur
cur->next = temp; // temp no longer points to a valid node
工作版本看起来更像这样:
template <class T>
bool LinkedList<T>::remove(const T object) {
// Iterate through the list.
for(Node<T> **cur = &head;; cur = &((*cur)->next)) {
// Check for list end.
if(!*cur)
return false;
// Check for match.
if((*cur)->value == object)
break;
}
// Knock out the node.
Node<T> *temp = (*cur)->next;
delete *cur;
*cur = temp;
// No idea what s does.
--s;
return true;
}