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

递归反转链表添加打印语句后程序挂起的问题

递归反转链表添加打印语句后程序挂起的问题

嘿,我完全懂你遇到的这个坑!你这个问题根本不是递归反转函数的逻辑问题,罪魁祸首其实是你自定义的ListNode.__repr__方法,在打印节点的时候不小心触发了无限循环。

咱们来捋清楚原因:当你在递归反转的过程中打印head节点时,Python会自动调用__repr__方法来生成节点的字符串表示。而你的__repr__是通过遍历整个链表直到next为None来拼接字符串的——但在递归反转的中间步骤里,链表的结构是部分成环的!

举个具体例子:假设原链表是1->2->3,当递归执行到处理节点2的时候,节点3已经被反转成新的头节点,而且节点3的next已经被改成指向节点2了(这是反转过程中的临时状态)。这时候你打印节点2,__repr__里的while循环会走2->3->2->3->...,永远找不到next为None的节点,程序自然就挂住不动了。

给你两个简单的解决方案:

方案一:修改__repr__方法,避免无限遍历

给遍历过程加个步数限制,防止陷入环里出不来:

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

    def __repr__(self):
        next_node = self.next
        val = self.val
        out = f"ListNode({val}, "
        count_paren = 1
        max_steps = 10  # 限制最大遍历步数,调试足够用了
        steps = 0
        while next_node is not None and steps < max_steps:
            val = next_node.val
            out += f"ListNode({val}, "
            next_node = next_node.next
            count_paren += 1
            steps += 1
        # 如果超出步数,说明可能有环,用省略号表示
        if next_node is not None:
            out += "...)"
        else:
            out += f"{next_node}"
            out += count_paren * ")"
        return out

方案二:简化调试打印,只打印当前节点的关键信息

不用打印整个节点对象,只打印当前节点的值和它的下一个节点值,这样就不会触发完整的链表遍历:

def reverse(head):
    if not head or not head.next:
        return head
    # 只打印当前节点的val和next的val,避免触发__repr__的全链表遍历
    print("1 HEAD val", head.val, "next val", head.next.val if head.next else None)
    new_head = reverse(head.next)
    head.next.next = head
    head.next = None
    return new_head

放心,你的递归反转逻辑本身是没问题的,只是调试打印的方式踩了__repr__的坑~

备注:内容来源于stack exchange,提问作者strboul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 11:27:58