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

LinkedList merge_sorted函数陷入无限循环,请求技术排查与解决

链表合并函数无限循环的修复方案

你的代码触发无限循环的核心原因是初始化阶段没有移动已选中的链表指针:
当你把new_root和new_tail指向curr1或curr2后,对应的curr1/curr2仍然停留在原链表的起始位置。进入while循环的第一次迭代时,会把new_tail.nxt再次指向这个未移动的指针,直接在新链表中形成环,导致后续遍历陷入死循环。

修复后的代码

def merge_sorted(root1, root2):
    """Ascending Order"""

    if root1 is None:
        return root2
    
    if root2 is None:
        return root1
    
    curr1 = root1
    curr2 = root2
    new_root = None
    new_tail = None

    # 初始化新链表的头和尾
    if curr1.val > curr2.val:
        new_root = curr2
        new_tail = curr2
        curr2 = curr2.nxt  # 关键:已加入新链表,指针后移
    else:  # curr1.val <= curr2.val
        new_root = curr1
        new_tail = curr1
        curr1 = curr1.nxt  # 关键:已加入新链表,指针后移

    # 合并过程
    while curr1 and curr2:
        if curr1.val > curr2.val:
            new_tail.nxt = curr2
            new_tail = new_tail.nxt
            curr2 = curr2.nxt
        else:
            new_tail.nxt = curr1
            new_tail = new_tail.nxt
            curr1 = curr1.nxt

    # 拼接剩余节点
    if curr1:
        new_tail.nxt = curr1
    if curr2:
        new_tail.nxt = curr2

    return new_root        

额外优化建议

  • 用is None代替== None,这是Python中判断空值的更规范写法
  • 合并剩余节点的部分可以简化成new_tail.nxt = curr1 or curr2,逻辑完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:30:11