Reputation: 8879
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
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
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