Skip to content

Latest commit

 

History

History
48 lines (33 loc) · 823 Bytes

021._merge_two_sorted_lists.md

File metadata and controls

48 lines (33 loc) · 823 Bytes

###21. Merge Two Sorted Lists

题目:

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

难度: Easy

同样适用dummy head

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        
        dummy = ListNode(-1)
        cur = dummy
        
        while l1 and l2:
            if l1.val < l2.val:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        
        if l1:
            cur.next = l1
        else:
            cur.next = l2
        return dummy.next