0

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

}
AstroCB
  • 12,337
  • 20
  • 57
  • 73
user2896852
  • 57
  • 1
  • 6

4 Answers4

2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • +1 and I think you can take advantage of having a `for` and declare `next` with the same scope. Just for fun ;-) (as in my comment to the question). – Michael Krelin - hacker Oct 26 '13 at 19:42
  • 1
    Since you are wiping out the list, you can actually move `top` along the list as you go and not have to clear it when you are done. – Zac Howland Oct 26 '13 at 19:49
0

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;
}
digital_revenant
  • 3,274
  • 1
  • 15
  • 24
0

Think this is what you wanted to do:

node *current = top;
while(current != NULL);
{
    node *temp = current->next;
    delete current;
    current = temp;
}
top = null;
Bozemoto
  • 226
  • 2
  • 6
0
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.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42