python链表中相同代码的两种输出

问题描述 投票:0回答:1
    else:
        n = self.head
        while n.ref is not None:
            n = n.ref
        n.ref = new_node

** 输出 -> 30 20 10**

  • 如果我执行此代码 o/p 是正确的 *

      else:
          while self.head.ref is not None:
              self.head = self.head.ref
          self.head.ref = new_node
    

** 输出 -> 30 10**

  • 如果我执行此代码,o/p 将跳过中间数字并仅执行最后一个。 *
python data-structures linked-list singly-linked-list
1个回答
0
投票

在代码的第二部分,您基本上是在重新分配链表的头部。这就是为什么你得到不同的结果。
它与 Python 的命名空间以及它如何将变量名称分配给对象(例如 int、float...)有关。
在第一个代码中,您有

n
指的是链表的头部。然后再次在循环中,将另一个引用重新分配给
n
。你告诉 python 忽略
n
引用的前一个对象并指向另一个对象。
但是在第二个代码中,您正在将链接的头部更改为它的下一个对象引用。这就是为什么你会得到两个不同的结果。

© www.soinside.com 2019 - 2024. All rights reserved.