[英]Python: How to Completely delete Linked List?
Lets say that I have such class definition for Node
假设我有这样的
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.我还有指向链表开头的
head
变量。
Is it enough to set head = None
to completely delete linked list?设置
head = None
是否足以完全删除链表? I suppose gc should do it's work?我想 gc 应该做它的工作?
I compare it to c/c++
where you should still iterate over whole list and free every element.我将它与
c/c++
进行比较,在c/c++
中您仍然应该遍历整个列表并释放每个元素。
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.当
head
变量的生命周期结束时,如果您没有对该列表的任何其他引用,该列表将变得不可访问并自动符合收集条件。 On CPython, it'll usually get collected immediately, but you shouldn't rely on that.在 CPython 上,它通常会立即被收集,但您不应该依赖它。
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
.如果要在
head
变量的生命周期结束之前使列表符合收集条件,则设置head = None
将起作用, del head
。 (Note that del
means "unset this variable", not "delete this object".) (请注意,
del
意思是“取消设置此变量”,而不是“删除此对象”。)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.