Simple to understand python code that runs 49ms and beats 91.40%


  • 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
            """
            rethead=ListNode(0)
            dump=rethead
            # when l1 and l2 both still have memebers
            while(l1 and l2):
                # although the order is not in the question, found this on OJ
                if((l1.val)>(l2.val)):
                    #assign the smaller node to our list
                    rethead.next=l2
                    # move the used list to the next member
                    l2=l2.next
                else:
                    # if l1 is smaller, the we assign l1 node to our list
                    rethead.next=l1
                    l1=l1.next
                # after that we move to next one of our list
                rethead=rethead.next
            if(l1):
                rethead.next=l1
            else:
                rethead.next=l2
            
            return dump.next
                
    

Log in to reply
 

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