为什么最后一个节点没有被删除链表?

时间:2016-06-30 17:25:13

标签: python python-2.7 linked-list

我有以下代码。我想删除最后一个节点。但是节点没有被删除。 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)

2 个答案:

答案 0 :(得分:2)

您应该取消引用最后一个节点,而不是使用del

替换

if root.next != None and myfrontptr.next == None:
    del myfrontptr

使用

if root.next != None and myfrontptr.next == None:
    root.next = None

答案 1 :(得分:1)

您忘记在删除最后一个元素的最后一个元素之前的元素中设置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 # you don't need this, myfrontptr is a local name anyway
        root.next = None
    return temp

del does not remove anything from memory。在python memory is freed by Garbage Collector中用C / C ++取消。即使在C / C ++中,你也必须覆盖最后一个元素指针/引用。