mq029.合并两个有序链表

 

题目链接

做过这个题了,比较清晰吧就不多说了,啊当然官网的解答更加简洁(这启发了我不要用or系列的,或许一开始都先用and的就好,然后剩下只有一个链表(其他情况下可能是列表或者数组之类的)的时候再讨论(如这里所示完全可以合在一起判断))。这个算法的时间复杂度是O(N),空间复杂度是O(1)。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = new = ListNode(None)
        while l1 or l2:
            if l1 and l2:
                if l1.val <= l2.val:
                    new.next = l1
                    l1 = l1.next
                else:
                    new.next = l2
                    l2 = l2.next
            elif l1 and not l2:
                new.next = l1
                l1 = l1.next
            elif not l1 and l2:
                new.next = l2
                l2 = l2.next
            new = new.next
        return dummy.next

    def mergeTwoLists2(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