编写 LinkedList 析构函数?

2022-01-01 00:00:00 linked-list destructor c++

这是一个有效的 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;

相关文章