不知道如何在 c++ 中清除链表?
Can't figure out how to clear a linked list in c++?
我正在尝试弄清楚如何清除堆栈(以链表的形式)。链表不是我的强项;我完全不明白他们。这是我的代码,任何人都可以阐明为什么它不起作用吗?当我尝试通过 main 中的开关调用该方法时,它似乎也陷入了无限循环。
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
指针(从而把地毯拉到你自己的脚下,可以这么说)。
就像
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)
{
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;
}
}
整个块可以替换为:
while (top != nullptr)
{
unique_ptr<node> p(top);
top = top->next;
}
如果列表已为空,则不执行任何操作。 如果它不为空,unique_ptr
控制当前top
的内存管理(这将在循环迭代之间将其删除),将top
移动到next
。 当top
NULL
时,所有内容都被清除,top
设置为NULL
。
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 为什么C中的通用链表中存储的数据已损坏
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表c++插入,所有情况都已检查,但没有任何工作
- 不知道如何在 c++ 中清除链表?
- 我将如何清除链表
- 如何使用析构函数清除链表内存,而不会出现valgrind错误?[更新:操作员过载帮助]