我将如何在不损坏列表的情况下删除链表中的节点
How would I go about deleting a node in a linked list without corrupting the list?
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;
}
相关文章:
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- 类(可能是代理)的命名,允许在不修改基础容器的情况下对项目进行排序和删除
- 在不使用任何 STL 容器的情况下删除重复项
- 如何在不泄漏内存的情况下删除链接列表
- 使用QT,如何在不读取整个文件的情况下删除文本文件中的第一行
- C++ 如何在不丢失内存的情况下删除节点
- 如何在没有递归的情况下删除链接列表
- 在只给定单个链接列表中间的节点的情况下删除该节点.C++
- 在不使用虚拟析构函数的情况下删除继承的对象时中止
- 检查目录树是否可以在不实际开始删除的情况下删除
- 如何在不知道其类型的情况下删除结构
- C++ 在不知道位置的情况下删除矢量中的特定值
- 如何在不导入任何库的情况下删除矢量
- 重写类运算符new并在不更改类的情况下删除
- 如何在无权访问的情况下删除对象
- 我将如何在不损坏列表的情况下删除链表中的节点
- Qmake:如何在不更改Qmake .conf的情况下删除某个项目的编译器标志
- 我可以在不检查是否存储该对象的情况下删除联合组件吗?
- 内存管理 - 是否可以在不调用析构函数的情况下删除 c++ 中的对象
- 我可以在不中断代码的情况下删除此警告吗?