问题
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