双链表-垃圾回收 [英] doubly linked list - garbage collection

查看:73
本文介绍了双链表-垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个双向链接列表.我的列表仅包含2个元素(假设 node1 node2 ),我想删除指向第一个节点的 head 指针( node1 ).因为在Cpython中,垃圾回收的主要算法是引用计数.

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.

现在我的问题是-( Example-1 ),如果我将 self.head 设置为 self.head = self.head.next 并将 node2 prev (上一个)属性设置为 None -这是否会从内存中完全删除第一个节点?因为 node1 现在没有其他引用了.还是必须调用第二个示例(Example-2)中所示的 del 方法?从内存中完全删除 node1 的正确方法是什么?

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?

示例1:

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

示例2:

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

推荐答案

通过 del self.head ,您删除对节点的引用,而不是节点本身.通过重新分配,对该节点的引用将丢失.通常,以两种方式,都没有指向下一个节点的内容.通常,只要没有引用,Python就会从内存中删除某些内容.因此,在您的情况下,两者都具有相同的结果.我希望只重新分配,而不删除

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:当然,假设引用没有保留在代码中的其他地方

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

这篇关于双链表-垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆