doubly linked list - garbage collection

不羁岁月 提交于 2021-02-05 07:58:47

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/40935681/doubly-linked-list-garbage-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!