Writing a LinkedList destructor?(编写 LinkedList 析构函数?)
问题描述
这是一个有效的 LinkedList 析构函数吗?我还是被他们弄糊涂了.
Is this a valid LinkedList destructor? I'm still sort of confused by them.
我想确保我理解正确.
LinkedList::~LinkedList()
{
ListNode *ptr;
for (ptr = head; head; ptr = head)
{
head = head->next
delete ptr;
}
}
因此在循环开始时,指针 ptr 被设置为保存 head 的地址,即列表中的第一个节点.然后将 head 设置为下一项,一旦发生第一次删除,它将成为列表的开头.ptr 被删除,第一个节点也被删除.在循环的第一次迭代中,指针再次设置为 head.
So at the beginning of the loop, pointer ptr is set to hold the address of head, the first node in the list. head is then set to the next item, which will become the beginning of the list once this first deletion takes place. ptr is deleted, and so is the first node. With the first iteration of the loop, pointer is set to head again.
让我担心的是到达最后一个节点.条件头";应该检查它是否为空,但我不确定它是否有效.
The thing that concerns me is reaching the very last node. The condition "head;" should check that it is not null, but I'm not sure if it will work.
感谢任何帮助.
推荐答案
为什么不做得更简单 - 使用优雅的 while
循环,而不是尝试仔细分析是否过度编译了 for
-loop 是否正确?
Why not do it much much simpler - with an elegant while
-loop instead of trying to carefully analyze whether that overcompilcated for
-loop is correct?
ListNode* current = head;
while( current != 0 ) {
ListNode* next = current->next;
delete current;
current = next;
}
head = 0;
这篇关于编写 LinkedList 析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:编写 LinkedList 析构函数?
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01