在python中删除整个链表

在python中删除整个链表,python,singly-linked-list,Python,Singly Linked List,我编写了一个程序,创建一个单链表,现在我正试图删除整个列表 首先,我将self.head指定给一个名为current的变量,但该函数不起作用,程序将打印整个列表 “”“ “”“ 结果: 但是,当我更改代码时,打印列表的程序是空的 新代码: “”“ “”“ 结果: 我不明白为什么第二个代码有效,而第一个代码无效。当我使用变量而不是self.head时,为什么没有删除节点?如果打印current和self.head的内存地址,您会看到它们不一样,因为当您执行current=None时,curre

我编写了一个程序,创建一个单链表,现在我正试图删除整个列表

首先,我将self.head指定给一个名为current的变量,但该函数不起作用,程序将打印整个列表

“”“

“”“

结果:

但是,当我更改代码时,打印列表的程序是空的

新代码:

“”“

“”“

结果:


我不明白为什么第二个代码有效,而第一个代码无效。当我使用变量而不是self.head时,为什么没有删除节点?

如果打印current和self.head的内存地址,您会看到它们不一样,因为当您执行current=None时,current指向另一个内存大小写(其中包含None值),但这不会影响self.head变量。这就是为什么第一个代码的列表不是空的

def删除(自):
电流=自身磁头
打印(“当前地址=”+十六进制(id(当前)))
打印(“self.head address=“+hex(id(self.head)))
虽然当前值不是“无”:
nextNode=current.next
电流=无
打印(“当前地址=”+十六进制(id(当前)))
打印(“self.head address=“+hex(id(self.head)))
当前=下一个节点
输出:

current adress = 0x7f9304ecdcd0  //print before while current = self.head so same address
self.head adress = 0x7f9304ecdcd0
current adress = 0x90a9f0     //current = None so current address change
self.head adress = 0x7f9304ecdcd0 //self.head doesn't change
current adress = 0x90a9f0
self.head adress = 0x7f9304ecdcd0
def deleteLinkedList(self):
          
    while self.head is not None:
        nextNode = self.head.next
        self.head = None
        self.head = nextNode
current adress = 0x7f9304ecdcd0  //print before while current = self.head so same address
self.head adress = 0x7f9304ecdcd0
current adress = 0x90a9f0     //current = None so current address change
self.head adress = 0x7f9304ecdcd0 //self.head doesn't change
current adress = 0x90a9f0
self.head adress = 0x7f9304ecdcd0