My Python solution using a guard node


  • 12
    S
    def mergeTwoLists(self, l1, l2):
            if not l1 and not l2:
                return None
            
            node = guard_node = ListNode(0)
            
            while l1 and l2:
                if l1.val <= l2.val:
                    node.next = l1
                    l1 = l1.next
                else:
                    node.next = l2
                    l2 = l2.next
                node = node.next
            
            if l1 or l2:
                node.next = l1 or l2
            
            return guard_node.next

  • 0
    Z

    Thanks for sharing! Very clean code and easy to understand :)


  • 0
    Z

    Could you please explain more about if l1 or l2: p.next = l1 or l2? I've never seen expression like this before. What happened if there multiple nodes of l1 or l2 left? Thanks a lot!


  • 0
    S

    it assigns a value of l1 or l2 to node.next if either of l1 or l2 has valid (not null) data. e.g a = 1 or None (or) a = None or 1 assigns a value of 1 to a.


  • 0
    Q

    amazing! I never known that the judge condition can be wrote as "if l1 or l2: ... l1 or l2", thank for your tip!!!


  • 1
    H
    if not l1 and not l2:
                return None
    

    you can remove it and it is exactly my soluton then:)

    forget to add:

    change

     if l1 or l2:
                node.next = l1 or l2
    

    to
    node.next = l1 or l2


  • 3
    C

    Nice solution, here is a shorten version of your code:

    def mergeTwoLists(self, l1, l2):
        head = dummy = ListNode(0)
        while l1 and l2:
            if l1.val < l2.val:
                head.next = ListNode(l1.val)  # or l1
                l1 = l1.next
            else:
                head.next = ListNode(l2.val)  # or l2
                l2 = l2.next
            head = head.next
        head.next = l1 or l2
        return dummy.next

  • 0
    Z

    Very nice code !


  • 0
    T

    Here is a more condensed version:

    def mergeTwoLists(self, l1, l2):
        node = dummy = ListNode(-1)
        while l1 and l2:
            if l1.val >= l2.val: 
                l1, l2 = l2, l1
            node.next = l1
            l1 = l1.next 
            node = node.next
        node.next = l1 or l2
        return dummy.next
    

  • 0
    Z

    @totolipton what ListNode(0) does? I am new to programming so just want to understand if someone give me details of it.


  • 0
    Y

    @zorro13 It's just a dummy node


Log in to reply
 

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