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**
在代码的第二部分,您基本上是在重新分配链表的头部。这就是为什么你得到不同的结果。
它与 Python 的命名空间以及它如何将变量名称分配给对象(例如 int、float...)有关。
在第一个代码中,您有
n
指的是链表的头部。然后再次在循环中,将另一个引用重新分配给n
。你告诉 python 忽略 n
引用的前一个对象并指向另一个对象。