C++ Can';我不知道如何在c+中清除链表+;?
我试图弄清楚如何清除堆栈(以链表的形式)。链表不是我的专长;我一点也不懂。这是我的代码,有人能解释一下为什么它不起作用吗?当我试图通过main中的开关调用该方法时,它似乎陷入了无限循环C++ Can';我不知道如何在c+中清除链表+;?,c++,list,linked-list,stack,C++,List,Linked List,Stack,我试图弄清楚如何清除堆栈(以链表的形式)。链表不是我的专长;我一点也不懂。这是我的代码,有人能解释一下为什么它不起作用吗?当我试图通过main中的开关调用该方法时,它似乎陷入了无限循环 void stack :: clearStack() { if (isEmpty()== true) { cout << "\nThere are no elements in the stack. \n"; } else { node *current = top; no
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;
}
}
}
void stack::clearStack()
{
如果(isEmpty()==true)
{
下一步;
删除当前文件;
电流=温度;
}
}
}
该代码存在一些问题。第一个是取消对未初始化指针(temp
)的引用,另一个是在循环之前删除下一个指针(也就是说,在自己脚下拉出地毯)
这很简单
node* next;
for (node* current = top; current != nullptr; current = next)
{
next = current->next;
delete current;
}
哦,完成后别忘了清除top
。您还没有初始化temp
。您需要将temp
设置为列表的第一个节点。在循环中,循环遍历节点并不断删除它们
node *current = top;
node *temp = top; // initialize temp to top
while(current != NULL);
{
temp = temp -> next; // increase temp
delete current;
current = temp;
}
认为这就是你想要做的:
node *current = top;
while(current != NULL);
{
node *temp = current->next;
delete current;
current = temp;
}
top = null;
if(isEmpty()==true)
{
下一步;
删除当前文件;
电流=温度;
}
}
整个区块可替换为:
while (top != nullptr)
{
unique_ptr<node> p(top);
top = top->next;
}
while(顶部!=nullptr)
{
唯一的ptr p(顶部);
顶部=顶部->下一步;
}
如果列表已为空,则不会执行任何操作。如果它不是空的,unique\u ptr
控制当前top
的内存管理(这将在循环迭代之间删除它),将top
移动到下一个。当top
为NULL
时,所有内容都被清除,并且top
设置为NULL
,看起来您正在使用temp
而不必进行初始化。我认为您应该阅读更多内容,并尝试更好地理解它们对于(node*p=top,*t;p=t)t=p->下一步,删除p代码>在while结尾的分号也没有用…下面的大多数答案只是复制了它,所以它们也不起作用。+1我认为你可以利用为
设置一个,并在相同的范围内声明下一个
。只是为了好玩;-)(如我对问题的评论中所述)。由于您正在清除列表,因此您实际上可以在执行过程中沿列表移动top
,而不必在完成后清除列表。
while (top != nullptr)
{
unique_ptr<node> p(top);
top = top->next;
}