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;
}
我在分配后删除对象。当我打印出这些值时,节点似乎已损坏。这是从链表中删除项目的最佳方式吗?
最佳答案
Nodes destructor is just "delete next".
糟糕。如果每个节点在其析构函数中删除下一个节点,这将导致从该点开始的整个列表被删除!
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
关于c++ - 我将如何在不破坏链表的情况下删除链表中的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9575778/