python - merge sorted lists - easy to understand


  • 0
    S
    # 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
            """
            l3, l4 = None, None
            while l1 != None and l2 != None:
                if l1.val < l2.val:
                    if l3 == None:
                        l3 = l4 = l1
                    else:
                        l4.next = l1
                        l4 = l4.next
                    l1 = l1.next
                else:
                    if l3 == None:
                        l3 = l4 = l2
                    else:
                        l4.next = l2
                        l4 = l4.next
                    l2 = l2.next
            
            if l1 != None:
                if l3 == None:
                    l3 = l4 = l1
                else:
                    l4.next = l1
            
            if l2 != None:
                if l3 == None:
                    l3 = l4 = l2
                else:
                    l4.next = l2
            
            return l3
                    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.