Merge Two Sorted Lists

LeetCode

Question

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Solution

First define class ListNode, it has a method make_list

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
   def make_list(elements):
      head = ListNode(elements[0])
      for element in elements[1:]:
         ptr = head
         while ptr.next:
            ptr = ptr.next
         ptr.next = ListNode(element)
      return head
      
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
def mergeTwoLists(l1, l2):
  if not l1:
    return l2
  if not l2:
    return l1
  if(l1.val<=l2.val):
    l1.next = mergeTwoLists(l1.next,l2)
    return l1
  else:
    l2.next = mergeTwoLists(l1,l2.next)
    return l2
         
head1 = ListNode.make_list([1,2,4,7])
head2 = ListNode.make_list([1,3,4,5,6,8])

head3 = mergeTwoLists(head1,head2)
print_list(head3)
## [1, 1, 2, 3, 4, 4, 5, 6, 7, 8, ]

Summary

The key is to understand linked list and use recursive to solve this question.

Zhe Lu
Zhe Lu
Graduate student & Research assistant

A graduate student pursuing the knowledge of data science.