我有下面的代码。我正在尝试删除最后一个节点。但是节点没有被删除。temp
仍然保持着所有的data
。我不明白,在Python中赋值意味着deep copy or shallow copy
?
class ll:
def __init__(self, data):
self.data = data
self.next = None
def adddata(self, data):
if not self.next:
self.next = ll(data)
return
self.next.adddata(data)
def display(root):
if root == None:
return
print root.data
display(root.next)
def delete_last(root):
temp = root
myfrontptr = root.next
while myfrontptr.next != None:
root = root.next
myfrontptr = myfrontptr.next
if root.next != None and myfrontptr.next == None:
del myfrontptr
return temp
l = ll(1)
l.adddata(5)
l.adddata(3)
l.adddata(2)
l.adddata(0)
l.adddata(4)
l = delete_last(l)
display(l)
您应该取消引用最后一个节点,而不是使用del
。
if root.next != None and myfrontptr.next == None:
del myfrontptr
if root.next != None and myfrontptr.next == None:
root.next = None
当最后一个元素被移除时,您忘记在最后一个元素之前设置next
reference:
def delete_last(root):
temp = root
myfrontptr = root.next
while myfrontptr.next != None:
root = root.next
myfrontptr = myfrontptr.next
if root.next != None and myfrontptr.next == None:
del myfrontptr # you don't need this, myfrontptr is a local name anyway
root.next = None
return temp
del
不会从内存中删除任何内容。在C/c++中,在python中内存由垃圾回收器释放。即使在C/c++中,你也必须覆盖最后一个元素指针/引用。