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

Python反转链表问题:代码无报错但仅输出None

链表反转代码问题排查与修复

问题分析

  • 无效头节点导致结构异常
    你手动执行了testlist.head = ListNode(None),这违背了LinkedList类的初始设计(类的__init__已将head设为None),会在链表头部插入一个值为None的无效节点,后续追加的1、2、3、4、5都挂在这个节点之后,直接干扰了链表的正常结构。

  • 反转结果未更新链表头
    reverseList方法正确返回了反转后的新头节点,但你调用时仅执行testlist.reverseList(testlist.head.next),没有将返回值赋值给testlist.head,原链表的头节点依然是那个值为None的无效节点,所以printLL只会输出None。

  • 数据插入与期望输出不匹配
    你期望输出4、3、2、1,但代码里追加了1、2、3、4、5,需调整插入的数据或截断逻辑来匹配预期。

修正后的代码

class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None
        
    def printLL(self):
        current = self.head
        while current:
           print(current.val)
           current = current.next
    
    def append(self, val):
       newNode = ListNode(val)
       if self.head:
           current = self.head
           while current.next:
               current = current.next
           current.next = newNode
       else:
           self.head = newNode
   
    def reverseList(self, head):
        prev , curr = None, head
        while curr:
            tmpval = curr.next
            curr.next = prev
            prev = curr
            curr = tmpval
        return prev
        
# 测试代码修正
testlist = LinkedList()
# 仅插入预期的4个值
testlist.append(1)
testlist.append(2)
testlist.append(3)
testlist.append(4)
# 将反转后的新头节点赋值给链表head
testlist.head = testlist.reverseList(testlist.head)
testlist.printLL()

执行修正后的代码,会输出4、3、2、1,符合预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:17:44