编写 LinkedList 析构函数? [英] Writing a LinkedList destructor?

查看:27
本文介绍了编写 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 析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆