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

梦想的初衷 提交于 2019-12-13 04:24:40

问题


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.

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

}

回答1:


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).

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.




回答2:


You have not initialized temp. You need to set temp to the first node of the list. 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;
}



回答3:


Think this is what you wanted to do:

node *current = top;
while(current != NULL);
{
    node *temp = current->next;
    delete current;
    current = temp;
}
top = null;



回答4:


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. When top is NULL, everything is cleared and top is set to NULL.



来源:https://stackoverflow.com/questions/19611008/cant-figure-out-how-to-clear-a-linked-list-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!