Python solution with detailed explanation


  • 0
    G

    Solution

    Merge Two Sorted Lists https://leetcode.com/problems/merge-two-sorted-lists/

    Algorithm

    • Organize the code well
    • Move common part to another method
    class Solution(object):
        def move(self, cur, temp):
            cur.next = temp
            cur = cur.next
            temp = temp.next
            cur.next = None
            return cur, temp
        
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            result = ListNode(None)
            cur = result
            while l1 or l2:
                if l1 == None:
                    cur, l2 = self.move(cur, l2)
                elif l2 == None:
                    cur, l1 = self.move(cur, l1)
                else:
                    if l1.val <= l2.val:
                        cur, l1 = self.move(cur, l1)
                    else:
                        cur, l2 = self.move(cur, l2)
            return result.next
    

Log in to reply
 

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