删除整个链表

Deleting the whole Linked List

我无法理解每次我们实际上从内存中删除整个列表时,仅仅通过删除当前的特定节点是如何做到的。他们在这里创建了 current 并将其值作为 link 列表,但实际的 link 列表没有做任何更改。唯一对我有意义的是 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;  
} 

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

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

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

坦率地说,如果您在所有这些结束之前不在 *head_ref 中留下悬空指针,而是使用 that ,这会更容易理解实际的迭代。即

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,之前包含的所有节点都将被销毁。任何时候都不会出现悬挂指针。