无法弄清楚如何清除c ++中的链表? [英] Can't figure out how to clear a linked list in c++?
问题描述
我试图弄清楚如何清除堆栈(以链表的形式).链接列表不是我的强项.我一点都不明白.这是我的代码,有人可以阐明为什么它不起作用吗?当我尝试通过main中的一个开关调用该方法时,似乎也陷入了无限循环.
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;
}
}
}
推荐答案
该代码存在一些问题.首先是您取消引用未初始化的指针(temp
),而在循环之前先取消引用delete
next
指针(这样可以说是在您自己的脚下拉了地毯).
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).
就这么简单
node* next;
for (node* current = top; current != nullptr; current = next)
{
next = current->next;
delete current;
}
哦,别忘了完成后清除top
.
Oh, and don't forget to clear top
when you're done.
这篇关于无法弄清楚如何清除c ++中的链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!