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

LeetCode 24题 Swap Nodes in Pairs Python代码报AttributeError求助

问题分析与修复

错误原因

你的代码存在两个关键问题:

  • 空指针访问错误:循环内更新指针时,curr = next_pair后直接执行curr_adj = curr.next,未判断curr是否为None。当链表处理到末尾(比如curr变为None),访问None.next会触发AttributeError。
  • 返回值错误:你返回的是原链表的head,但第一次交换后,新链表的头节点已经是原链表的第二个节点(比如示例中的节点2),原head已变为第二个节点,直接返回会导致结果错误。

修复后的代码

class Solution(object):
    def swapPairs(self, head):
        # 虚拟头节点,统一处理边界场景
        dummy = ListNode(0)
        dummy.next = head
        prev = dummy
        
        while prev.next and prev.next.next:
            # 标记当前要交换的两个节点
            first = prev.next
            second = prev.next.next
            
            # 执行节点交换
            first.next = second.next
            second.next = first
            prev.next = second
            
            # 移动指针到下一对节点的前置位置
            prev = first
        
        return dummy.next

代码说明

  • 虚拟头节点:用dummy节点简化链表头部的交换逻辑,无需单独处理头节点变更的边界情况。
  • 指针操作逻辑:每次交换前记录prev(当前节点对的前置节点)、first和second(待交换的两个节点),通过调整三者的指向完成交换,再将prev移动到first,为下一次交换做准备。
  • 循环条件:prev.next and prev.next.next确保存在至少两个可交换的节点,从根源避免空指针访问。

原逻辑的局部修正(保留你的核心思路)

如果不想用虚拟头节点,也可以这样修改:

class Solution(object):
    def swapPairs(self, head):
        if not head or not head.next:
            return head
        
        # 保存新的头节点
        new_head = head.next
        curr = head    
        prev = None  # 记录前一对节点的尾部,用于连接
        
        while curr and curr.next:
            curr_adj = curr.next
            next_pair = curr.next.next 

            # 交换节点
            curr_adj.next = curr   
            curr.next = next_pair  

            # 连接前一对与当前交换后的节点
            if prev:
                prev.next = curr_adj
            
            # 更新指针
            prev = curr
            curr = next_pair
        
        return new_head

这里新增prev指针处理节点对之间的连接,返回new_head(原链表第二个节点),同时确保仅当curr存在时才访问其next属性。

内容的提问来源于stack exchange,提问作者The Last Code Bender

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:25:16