【问题标题】:Deleting entire linked list in python在python中删除整个链表
【发布时间】:2021-06-07 10:08:13
【问题描述】:

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

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

"""

def deleteLinkedList(self):
        
    current = self.head
    while current is not None:

        nextNode = current.next
        current = None
        current = nextNode

"""

结果:

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

新代码:

"""

def deleteLinkedList(self):
          
    while self.head is not None:
        nextNode = self.head.next
        self.head = None
        self.head = nextNode

"""

结果:

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

【问题讨论】:

    标签: python singly-linked-list


    【解决方案1】:

    如果您打印 current 和 self.head 的内存地址,您会发现它们不一样,因为当您执行 current = None 时,current 指向另一个内存案例(包含 None 值)但它不影响你的 self.head 变量。这就是为什么您的第一个代码不为空的原因。

    def delete(self):
            current = self.head
            print("current adress = " + hex(id(current)))
            print("self.head adress = " + hex(id(self.head)))
            while current is not None:
                nextNode = current.next
                current = None
                print("current adress = " + hex(id(current)))
                print("self.head adress = " + hex(id(self.head)))
                current = 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
    

    【讨论】:

      猜你喜欢
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多