C++:删除单向链表中间的节点

C++: Deleting a node in the middle of a singly linked list?

本文关键字:中间 节点 链表 删除 C++      更新时间:2023-10-16

这是我的代码:

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;
}