合并两个有序链表

  • 方法1:迭代

    m、n为两个有序链表的长度

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

    空间复杂度:O(1)

    class ListNode:
        def __init__(self, val=0, next=None):
            self.val = val
            self.next = next
    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            prehead = ListNode(-1)
            pre = prehead
            while l1 and l2:
                if l1.val <= l2.val:
                    pre.next = l1
                    l1 = l1.next
                else:
                    pre.next = l2
                    l2 = l2.next
                pre = pre.next
            pre.next = l1 if l1 is not None else l2
            return prehead.next
    
  • 方法2:递归

    m、n为两个有序链表的长度

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

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

    class ListNode:
        def __init__(self,val=0,next=None):
            self.val = val
            self.next = next
    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            if not l1:
                return l2
            if not l2:
                return l1
            if l1.val <= l2.val:
                l1.next = self.mergeTwoLists(l1.next,l2)
                return l1
            else:
                l2.next = self.mergeTwoLists(l1,l2.next)
                return l2
        
    
posted @ 2020-06-25 02:42  guguda  阅读(109)  评论(0)    收藏  举报