Viacheslav Kondratiuk
Viacheslav Kondratiuk

Reputation: 8879

Python: How to Completely delete Linked List?

Lets say that I have such class definition for Node

class Node:
    def __init__(self, data, next):
        self.data = data
        self.next = next

Also I have head variable which points to the beginning of linked list.

Is it enough to set head = None to completely delete linked list? I suppose gc should do it's work?

I compare it to c/c++ where you should still iterate over whole list and free every element.

Upvotes: 1

Views: 4120

Answers (2)

Anil Ashok
Anil Ashok

Reputation: 1

def deleteAll(self):
    temp = self.head
    if temp is None:
        print("\n Not possible to delete empty list")
    while temp:
        self.head = temp.get_next()
        temp = None
        temp = self.head

Upvotes: 0

user2357112
user2357112

Reputation: 280456

Usually, you don't even need to do anything. When the lifetime of the head variable ends, if you don't have any other references to the list, the list will become unreachable and eligible for collection automatically. On CPython, it'll usually get collected immediately, but you shouldn't rely on that.

If you want to make the list eligible for collection before the head variable's lifetime ends, setting head = None would work, as would del head. (Note that del means "unset this variable", not "delete this object".)

Upvotes: 5

Related Questions