21. 合并两个有序链表

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

解法一:

创建一个新的头结点,同步遍历l1和l2,每次取较小者放入新链。

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        Head = ListNode(0)
        i = Head    #工作节点
        while l1 and l2:    #两链都不为空
            if l1.val < l2.val:
                i.next = l1
                l1 = l1.next
            else:
                i.next = l2
                l2 = l2.next
            i = i.next
        i.next = l1 if l1 else l2    #若有一个链为空,取另一个链
        return Head.next

最后更新于