首页 > 解决方案 > 删除整个链表

问题描述

我无法理解每次我们实际从内存中删除整个列表时如何删除当前的特定节点。在这里,他们创建了 current 并将其值作为链接列表,但没有对实际链接列表进行任何更改。唯一对我有意义的行head_ref = NULL;
是代码:

/* Function to delete the entire linked list */
void deleteList(Node** head_ref)  
{  
      
/* deref head_ref to get the real head */
Node* current = *head_ref;  
Node* next;  
  
while (current != NULL)  
{  
    next = current->next;  
    free(current);  
    current = next;  
}  enter code here
      
/* deref head_ref to affect the real head back  
    in the caller. */
*head_ref = NULL;  
} 

标签: c++pointerslinked-listnodes

解决方案


对于列表中的每个节点,您:

  1. 保存当前迭代指针值
  2. 将迭代指针前进到下一个列表节点。
  3. 删除(1)中获取的节点

重复此操作,直到迭代节点落在 NULL 上,这意味着列表的末尾。

*head_ref坦率地说,如果您在所有这些结束之前不留下一个悬空指针,而是将用于实际迭代,那么这更容易理解。IE。

void deleteList(Node** head_ref)
{
    while (*head_ref) // while we've not reached the end-of-list
    {
        Node *victim = *head_ref;  // 1. remember current node.
        *head_ref = victim->next;  // 2. advance head to next node.
        free(victim);              // 3. delete node from (1)
    }
}

完成上述操作后,列表头将为 NULL,并且先前包含的所有节点都将被销毁。任何时候都没有悬空指针。


推荐阅读