N Randhawa
N Randhawa

Reputation: 9521

doubly linked list - garbage collection

I have created a doubly linked list. My list contains only 2 elements (suppose node1 and node2) and I want to delete the head pointer which points to the first node (node1) in the list. Because in Cpython the primary algorithm for garbage collection is reference counting.

Now my question is -(Example-1) if I set the self.head to self.head = self.head.next and set node2 prev (previous) attribute to None - does this delete the first node completly from the memory? Because the node1 has now no other references. Or do have to call del method as shown in the second example (Example-2)? Which is the right way to delete the node1 completly from the meomory?

Example-1:

def remHead(self):
  temp=self.head.next
  self.head=self.head.next
  temp.prev=None

Example-2:

def remHead(self):
  temp=self.head.next
  del self.head
  self.head=temp
  self.head.prev=None

Upvotes: 1

Views: 269

Answers (1)

blue note
blue note

Reputation: 29099

By del self.head, you delete the reference to the node, not the node itself. By re-assigning, the reference to the node is lost. Normally, in both ways, there is nothing left pointing to the next node. In general, Python deletes something from memory as soon as there are no references to it. So, in your case both have the same result. I would prefer just reassigning, without deleting

PS: Of course, assuming that the references are not kept somewhere else in your code

Upvotes: 2

Related Questions