21. Merge Two Sorted Lists

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None and l2 is None:
            return None
        elif l1 is None:
            return l2
        elif l2 is None:
            return l1
        
        dummy = ListNode(8217)
        cur = dummy
        while(l1 and l2):
            if l1.val <= l2.val:
                cur.next = l1
                l1 = l1.next
                cur = cur.next
            else:
                cur.next = l2
                l2 = l2.next
                cur = cur.next
        
        if l1:
            cur.next = l1
        if l2:
            cur.next = l2
        
        return dummy.next
  1. Read carefully what the question [merge sorted list] is. Otherwise you would find out the misunderstanding may lead you to re-construct the code.

  2. In linked list, if there are multiple input, try to consider modifying both two of them at a time in the loop, AND also think about handling ONLY ONE input at a time.

  3. Eliminate bad cases first will help you get rid of some future design problems, since we have already make sure l1 and l2 are both not None.

Last updated