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 析构函数?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
