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

查看:98
本文介绍了编写LinkedList析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有效的LinkedList析构函数?我仍然对他们很困惑。

Is this a valid LinkedList destructor? I'm still sort of confused by them.

我想确保我能正确理解这一点。

I want to make sure I'm understanding this correctly.

 LinkedList::~LinkedList()
 {
   ListNode *ptr;

   for (ptr = head; head; ptr = head)
   {
     head = head->next
     delete ptr;
   }
}



因此在循环开始时,指针ptr设置为保存头的地址,列表中的第一个节点。然后将头设置为下一个项目,这将在该第一次删除发生后成为列表的开始。 ptr被删除,第一个节点也是如此。在循环的第一次迭代中,指针被重新设置为头。

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.

关注我的东西到达最后一个节点。条件head;

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.

任何帮助感谢。

推荐答案

为什么不做得简单得多 - 用优雅的 -loop而不是试图仔细分析是否overcompilcated 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天全站免登陆