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

Python多变量赋值反转链表:为何部分写法触发NoneType错误?

链表反转中Python多变量赋值导致的AttributeError问题解析

问题场景

在实现链表反转时,用临时变量的常规写法能正常运行,但换成部分Python多变量赋值写法时,会触发AttributeError: 'NoneType' object has no attribute 'next',尽管while循环已经判断了cur不为空。

完整代码示例

class SinglyLinkedListNode:
    def __init__(self, node_data):
        self.data = node_data
        self.next = None

class SinglyLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insert_node(self, node_data):
        node = SinglyLinkedListNode(node_data)
        if not self.head:
            self.head = node
        else:
            self.tail.next = node
        self.tail = node

def print_singly_linked_list(node, sep):
    while node:
        print(str(node.data), end=sep)
        node = node.next
    print()

def reverse(head):
    pre = None
    cur = head
    while cur:
        # 可正常运行的多变量赋值写法
        cur.next, pre, cur = pre, cur, cur.next
        # 以下三种写法会触发AttributeError
        # 写法1: cur, cur.next, pre = cur.next, pre, cur
        # 写法2: pre, cur, cur.next = cur, cur.next, pre
        # 写法3: cur, pre, cur.next = cur.next, cur, pre
    return pre

# 输入输出示例
if __name__ == '__main__':
    llist = SinglyLinkedList()
    for data in [1, 2, 3, 4, 5]:
        llist.insert_node(data)
    print("原链表:")
    print_singly_linked_list(llist.head, " ")
    reversed_head = reverse(llist.head)
    print("反转后链表:")
    print_singly_linked_list(reversed_head, " ")

问题原因分析

Python的多变量赋值规则是先计算右侧所有表达式的值,再按左侧顺序依次赋值,这是核心逻辑:

  1. 正常写法的执行逻辑
    cur.next, pre, cur = pre, cur, cur.next

    • 赋值前先获取右侧三个值:当前的pre、当前的cur、当前的cur.next(此时cur不为空,cur.next有效)
    • 按顺序赋值:先把pre赋给cur.next,再把当前cur赋给pre,最后把cur.next赋给cur。整个过程中,cur的修改是最后一步,不会提前变成None导致后续访问next出错。
  2. 报错写法的核心问题
    以写法1cur, cur.next, pre = cur.next, pre, cur为例:

    • 右侧先计算出cur.next(此时有效)、pre、cur
    • 赋值顺序为:先把cur.next赋给cur。如果当前cur是链表最后一个节点,cur.next就是None,此时cur被直接赋值为None
    • 接下来执行cur.next = pre,此时cur已经是None,自然触发'NoneType' object has no attribute 'next'错误

其他两种报错写法同理:在赋值过程中提前将cur改为None,后续再访问cur.next就会触发异常。while循环的判断仅在循环开始时生效,无法阻止循环体内部的赋值操作让cur提前变为None。

总结

多变量赋值的顺序直接影响执行结果,必须确保:

  • 先获取cur.next的值并完成存储
  • 最后再修改cur的指向
  • 避免在cur变为None后再访问其next属性

内容的提问来源于stack exchange,提问作者Andy Shell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:57:14