C++:删除单向链表中间的节点
C++: Deleting a node in the middle of a singly linked list?
这是我的代码:
template<class L>
Node<L>* LinkedList<L>::DeleteNode(L toDelete)
{
Node<L>* current;
Node<L>* trail;
if(head == NULL)
{
cout << "nnCannot delete from an empty list.nn";
}
else
{
if(head->next == NULL)
{
if(head->data == toDelete)
{
current = head;
delete current;
head = current;
tail = current;
cout << "nObject found. The list is now empty.n";
}
else
{
cout << "nObject not found.n";
}
}
else
{
current = head;
while(current->data != toDelete && current->next != NULL)
{
trail = current;
current = current->next;
}
if(current->data == toDelete)
{
if(current->next == NULL)
{
trail->next = NULL;
current = trail;
}
else
{
// having error here
trail->next = current->next;
current = trail;
delete trail;
}
cout << "nNode found and deleted.n";
}
else
{
cout << "nObject not found.n";
}
}
}
return head;
}
我标记了我遇到问题的特定行(尝试从中间删除节点时(当下一个不为空时((。我已经尝试了该块的多种变体,但仍然一无所获。
非常感谢所有帮助!
看起来您正在分配当前点的地址,与跟踪点相同,然后释放该资源,我认为这不是意图。
现在,您实际上正在拆分列表,因为您将当前重新分配给在删除跟踪之前指向跟踪(当您想要释放电流时,根据您的while循环指向要删除的内容(
更有意义的是:
trail->next = current->next;
delete current;
我不确定您的其他案例如何按预期工作......代码对我来说看起来很有趣。 例如,在列表末尾的情况下,您没有释放任何资源(但您只是删除了一些内容,为什么没有释放资源? 在删除头部的情况下,您丢失了列表,并在当前实现中创建了内存泄漏。
综上所述 - 这是一个好的开始,但我会退后一步,对你的链表应该提供的接口进行原型设计,以便有效,并列出可能的边缘情况(例如删除头部(。
在这个阶段,你只是在欺骗错误的节点:trail 持有最后一个节点,用于应删除的节点。试试这个:
{
trail->next = current->next;
delete current;
//you may want to add: current=trail->next; if you are planing to keep working with
// the rest of the list
}
您还应该查看您的代码块:
if(current->next == NULL)
{
trail->next = NULL;
current = trail;
}
你实际上不是在这里妄想,它真的应该是:
if((current->next == NULL)
{
trail->next = NULL;
delete current;
}
相关文章:
- 反向给定链表中的K节点
- 2D数组来自文本输入,中间有空格
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 我可以擦除 std::queue 中间的节点吗?
- 尝试删除链表的头部或中间节点时出错
- 如何在列表中间释放删除的节点,而没有阀门错误
- C++ 在链表中间插入新节点时出现问题
- 在单个链接列表中间删除一个节点,仅给定对该节点的访问
- 在只给定单个链接列表中间的节点的情况下删除该节点.C++
- 从单链列表的中间删除节点
- C++正在从列表中间删除节点
- 在双向链表的中间插入一个节点
- 单链表在中间添加节点
- 查找链表的中间节点
- C++:删除单向链表中间的节点
- 如何在单遍历中找到单个链表的中间节点(如果链表的长度未给定)
- 单链表的中间节点
- 添加带有链表的中间节点