Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete all nodes in doubly linked list?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading