不知道如何在 c++ 中清除链表?

Can't figure out how to clear a linked list in c++?

本文关键字:清除 链表 c++ 不知道      更新时间:2023-10-16

我正在尝试弄清楚如何清除堆栈(以链表的形式)。链表不是我的强项;我完全不明白他们。这是我的代码,任何人都可以阐明为什么它不起作用吗?当我尝试通过 main 中的开关调用该方法时,它似乎也陷入了无限循环。

void stack :: clearStack()
{
if (isEmpty()== true)
{
    cout << "nThere are no elements in the stack. n";
}
else 
{
    node *current = top;
    node *temp;
    while(current != NULL);
    {
        current = temp -> next;
        delete current;
        current = temp;
    }
}
}

该代码存在一些问题。第一种是你取消引用一个未初始化的指针(temp),另一个是在你循环之前delete next指针(从而把地毯拉到你自己的脚下,可以这么说)。

就像

node* next;
for (node* current = top; current != nullptr; current = next)
{
    next = current->next;
    delete current;
}

哦,完成后不要忘记清除top

您尚未初始化temp 。您需要将temp设置为列表的第一个节点。在循环中,循环浏览节点并不断删除它们。

node *current = top;
node *temp = top; //    initialize temp to top
while(current != NULL);
{
    temp = temp -> next; // increase temp
    delete current;
    current = temp;
}

认为这是你想要做的:

node *current = top;
while(current != NULL);
{
    node *temp = current->next;
    delete current;
    current = temp;
}
top = null;
if (isEmpty()== true)
{
    cout << "nThere are no elements in the stack. n";
}
else 
{
    node *current = top;
    node *temp;
    while(current != NULL);
    {
        current = temp -> next;
        delete current;
        current = temp;
    }
}

整个块可以替换为:

while (top != nullptr)
{
    unique_ptr<node> p(top);
    top = top->next;
}

如果列表已为空,则不执行任何操作。 如果它不为空,unique_ptr控制当前top的内存管理(这将在循环迭代之间将其删除),将top移动到next。 当top NULL时,所有内容都被清除,top设置为NULL