You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python遍历链表时原头节点为何改变?是否操作有误?

为什么未修改head变量但链表节点状态却改变了?

我编写了一段Python代码处理输入为[5,4,2,1]的LinkedList,代码中未直接修改head变量,但遍历过程中head指向的节点状态却发生了改变,最终head的next变为None。以下是我的代码及输出,请问这是为什么?

代码

class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        superhead = head
        print("Head starting:", head)
        curr2, prev2 = head, None
        print("curr2:", curr2)
        print("Superhead:", superhead)
        print("Head before while loop:", head)
        count = max = 0
        while curr2:
            print("\nInside while: Head", head)
            temp2 = curr2.next
            curr2.next = prev2
            prev2 = curr2
            curr2 = temp2
        print("\nHead end:", head)

输出

Head starting: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
curr2: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
Superhead: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
Head before while loop: ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}

Inside while: Head ListNode{val: 5, next: ListNode{val: 4, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}}
Inside while: Head ListNode{val: 5, next: None}
Inside while: Head ListNode{val: 5, next: None}
Inside while: Head ListNode{val: 5, next: None}

Head end: ListNode{val: 5, next: None}

原因解释

这是因为Python的对象引用特性:

  • head、superhead、curr2一开始都指向同一个ListNode对象(即值为5的首节点)。
  • 你确实没有修改head变量本身(没有让它指向其他对象),但你通过curr2修改了这个对象的next属性:第一次进入循环时,curr2就是head指向的节点,执行curr2.next = prev2(此时prev2为None),直接把该节点的next改成了None。
  • 后续循环中curr2会指向链表的其他节点,但head始终指向最初的那个首节点,所以它的next属性已经被修改为None,之后打印的自然就是这个状态。

简单来说:变量存储的是对象的引用,多个变量可以指向同一个对象,修改对象的属性会影响所有指向它的变量——不管你用哪个变量去修改的。

内容的提问来源于stack exchange,提问作者Utkirna Shinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 21:34:55