这是我的代码:
template<class L>
Node<L>* LinkedList<L>::DeleteNode(L toDelete)
{
Node<L>* current;
Node<L>* trail;
if(head == NULL)
{
cout << "\n\nCannot delete from an empty list.\n\n";
}
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;
}
我标记了遇到麻烦的特定行(尝试从中间删除节点时(当next不为null时))。我已经尝试了该块的多种变体,但仍然没有。
非常感谢所有帮助!
最佳答案
看来您正在分配当前点的地址,使其与路径点相同,然后释放该资源,我认为这不是目的。
现在,您实际上是在拆分列表,因为您正在重新分配电流,以便在删除路径之前立即指向路径(当您要释放电流时,这基于您的while循环指向您要删除的内容)
这样做更有意义:trail->next = current->next;delete current;
我不确定您的其他情况如何按预期工作...代码对我来说似乎很有趣。例如,在列表末尾的情况下,您没有释放任何资源(但是您只是删除了一些内容,为什么没有释放资源?)在删除头的情况下,您丢失了列表并在您当前的实现中造成了内存泄漏。
话虽这么说-这是一个好的开始,但我会退后一步,对链表应提供的有效接口进行原型设计,并列出可能的边缘情况(例如删除头部)。
关于c++ - C++:删除单链列表中间的节点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27239900/