[LeetCode21] Merge Two Sorted Lists

Description: Merge two sorted linked lists into a new sorted linked list and return it. The new linked list is formed by splicing all the nodes of the given two linked lists.

eg:

Input: 1->2->4, 1->3->4
 Output: 1->1->2->3->4->4
 
 
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        mylist=listnow=ListNode(0)
        while l1 and l2:
            if l1.val<l2.val:
                listnow.next=l1
                l1=l1.next
            else:
                listnow.next=l2
                l2=l2.next
            listnow=listnow.next
        listnow.next=l1 or l2
        return mylist.next

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324847586&siteId=291194637