博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

leetcode 21. 合并两个有序链表(伪代码)

Posted on 2025-04-07 10:49  steve.z  阅读(20)  评论(0)    收藏  举报

1. 伪代码


1. 递归版本
Function MergeTwoLists(l1, l2):
    If l1 is null:
        Return l2
    If l2 is null:
        Return l1

    If l1.value < l2.value:
        l1.next = MergeTwoLists(l1.next, l2)
        Return l1
    Else:
        l2.next = MergeTwoLists(l1, l2.next)
        Return l2



2. 循环遍历版本
Function MergeTwoLists(l1, l2):
    Create a dummy node with arbitrary value
    Set current to point to dummy

    While l1 is not null and l2 is not null:
        If l1.value < l2.value:
            current.next = l1
            l1 = l1.next
        Else:
            current.next = l2
            l2 = l2.next
        current = current.next

    If l1 is null:
        current.next = l2
    Else:
        current.next = l1

    Return dummy.next