封面

LeetCode 题解 · 合并两个有序链表

笔记日期
# LeetCode
# Python
# 链表

两条链都从小到大排列。只要盯住两个头,后面再长也不必提前看。用 tail 记住结果的尾巴,每摘下一个节点,就让 tail 向前走一步。

左边是 1 → 4,右边是 1 → 3。两个 1 相等,约定先接左边那个;接下来 4 遇到右边的 1,改接右边。再接 3,右链用完,剩下的 4 可以一口气挂到尾部。

class Solution:
    def mergeTwoLists(self, list1, list2):
        dummy = tail = ListNode(0)
        while list1 and list2:
            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next
        tail.next = list1 if list1 is not None else list2
        return dummy.next

如果一条链本就为空,循环一次也不会进入,返回的就是另一条原链。这里复用输入节点,时间 O(m+n),额外空间 O(1)。ListNode 由题目提供。

LeetCode 第 21 题

返回 LeetCode 题单 →