跳过正文
  1. leetcode 题解/

21_合并两个有序链表

·109 字·1 分钟

类型:链表

    1. 合并两个有序链表 💚

    https://leetcode-cn.com/problems/merge-two-sorted-lists/

    ❓ 将两个升序链表合并为一个新的 升序 链表并返回。

    💡 递归

    class Solution:
        def mergeTwoLists(self, l1, l2):
            if l1 is None:
                return l2
            elif l2 is None:
                return l1
            elif l1.val < l2.val:
                l1.next = self.mergeTwoLists(l1.next, l2)
                return l1
            else:
                l2.next = self.mergeTwoLists(l1, l2.next)
                return l2

    时间复杂度:O(m + n),空间复杂度:O(m + n)

    💡 迭代

    class Solution:
        def mergeTwoLists(self, l1, l2):
            prehead = ListNode(-1)
    
            prev = prehead
            while l1 and l2:
                if l1.val <= l2.val:
                    prev.next = l1
                    l1 = l1.next
                else:
                    prev.next = l2
                    l2 = l2.next            
                prev = prev.next
    
            # 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
            prev.next = l1 if l1 is not None else l2
    
            return prehead.next

    时间复杂度:O(m + n),空间复杂度:O(1)