c++ - 删除整个链表
问题描述
我无法理解每次我们实际从内存中删除整个列表时如何删除当前的特定节点。在这里,他们创建了 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;
}
解决方案
对于列表中的每个节点,您:
- 保存当前迭代指针值
- 将迭代指针前进到下一个列表节点。
- 删除(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,并且先前包含的所有节点都将被销毁。任何时候都没有悬空指针。
推荐阅读
- c# - 使用wingdi函数(SetWorldTransform)一起缩放和旋转
- mysql - org.mule.runtime.api.connection.ConnectionException
- javascript - 如何以角度解决区域感知承诺?
- r - 如何在管道工 api 中上传 xlsx 文件作为输入
- filesystems - Openstack - 创建实例 1 或 2 天后文件系统更改为只读模式。之后无法访问任何文件
- firebase - 注销时快照侦听器权限错误 - Kotlin/Firestore
- javascript - 如何将 getDownloadURL 设置为变量?
- wordpress - 我的 WordPress 插件除了 admin 没有显示
- javascript - setupProxy.js 路径在使用 http 代理中间件的 reactjs 应用程序中无法识别
- linux - 执行接受参数并在后台运行的 bash shell 脚本