简体   繁体   English

无法弄清楚如何在c ++中清除链表?

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

I'm trying to figure out how to clear a stack (in the form of a linked list). 我正在试图找出如何清除堆栈(以链表的形式)。 Linked lists aren't my forte; 链接列表不是我的强项; I don't understand them at all. 我根本不懂。 Here's my code, can anyone shed some light onto why it's not working? 这是我的代码,任何人都可以解释为什么它不起作用? When I try to call the method through a switch in main, it seems too get stuck in an infinite loop. 当我尝试通过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;
    }
}

}

There are a few problems with that code. 该代码存在一些问题。 The first is that you dereference an uninitialized pointer ( temp ) the other that you delete the next pointer before you loop (and thereby pulling the carpet out under your own feet, so to say). 第一个是你取消引用一个未初始化的指针( temp )另一个你在循环之前delete next指针(从而将地毯拉出自己的脚,所以说)。

It's as simple as 这很简单

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

Oh, and don't forget to clear top when you're done. 哦,当你完成时不要忘记清除top

You have not initialized temp . 你还没有初始化temp You need to set temp to the first node of the list. 您需要将temp设置为列表的第一个节点。 Inside the loop, cycle through the nodes and keep deleting them. 在循环内部,循环遍历节点并继续删除它们。

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

Think this is what you wanted to do: 认为这是你想要做的:

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

That whole block can be replaced by: 整个块可以替换为:

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

If the list is already empty, nothing is done. 如果列表已经为空,则不执行任何操作。 If it is non-empty, unique_ptr takes control of the memory management of the current top (which will delete it between loop iterations), move the top to the next . 如果它是非空的,则unique_ptr控制当前top的内存管理(将在循环迭代之间删除它),将top移动到next When top is NULL , everything is cleared and top is set to NULL . topNULL ,清除所有内容并将top设置为NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM