如何删除双向链表中的所有节点?

huangapple go评论87阅读模式
英文:

How to delete all nodes in doubly linked list?

问题

我很好奇删除双向链表中所有节点的正确方法是什么。

这是我的链表结构:

type ListNode struct {
	Data branch
	Next *ListNode
	Prev *ListNode
}

type doublyLinkedList struct {
	Head *ListNode
	Tail *ListNode
	Size int
}

如果我只是将Head和Tail节点指向nil,这样会起作用吗?

func deleteAllNodes(dl *doublyLinkedList) {
    dl.Head = nil
    dl.Tail = nil
    dl.Size = 0
}

如果是这样,那么所有的节点会发生什么?它们会被垃圾回收吗?

英文:

I'm curious as to what is the correct way of deleting all nodes in a doubly linked list.

Here's my linked list structure:

type ListNode struct {
	Data branch
	Next *ListNode
	Prev *ListNode
}

type doublyLinkedList struct {
	Head *ListNode
	Tail *ListNode
	Size int
}

Will it work if I just point the Head & Tail nodes to Nil?

func deleteAllNodes(dl *doublyLinkedList) {
    dl.Head = nil
    dl.Tail = nil
    dl.Size = 0
}

If so, what happens to all the nodes? Does it get garbage collected?

答案1

得分: 2

在引用计数环境中(如Rust中的Arc,C++、Swift中的shared_ptr等),这可能会导致内存泄漏。

这些节点之间可能存在相互引用,但没有其他对它们的引用。从图论的角度来看,被“删除”的节点形成了对象图的一个组件,现在是一个不连通的图。

任何具有追踪垃圾收集器的环境(包括Go)都可以处理这个问题。

首先,垃圾收集器将检测内存图的所有连接组件(那些从根引用(如全局变量、局部变量等)引用的对象)。这被称为“标记”阶段。然后,在第二个“扫描”阶段,它将删除所有不连通的组件。参考链接:https://en.wikipedia.org/wiki/Tracing_garbage_collection#Na%C3%AFve_mark-and-sweep

英文:

In a reference counted environment (Arc in Rust, shared_ptr in C++, Swift, etc.), this could leak.

The nodes may have references among themselves, but there's no other references to them. In graph theory terms, the nodes being "deleted" form a component of the object graph, which is now a disconnected graph.

Any environment with a tracing garbage collector (including Go) can handle this, no problem.

First, the GC will detect all connected components of the memory graph (those objects which are referenced from root references, like global variables, local variables, etc.). This is called the "mark" phase. Then, it will delete all disconnected components in a second "sweep" phase. https://en.wikipedia.org/wiki/Tracing_garbage_collection#Na%C3%AFve_mark-and-sweep

huangapple
  • 本文由 发表于 2022年6月21日 04:04:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/72692425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定