Merge Two Sorted Lists in Python

PythonServer Side ProgrammingProgramming

Suppose we have two sorted lists A and B. We have to merge them and form only one sorted list C. The size of lists may different.

For an example, suppose A = [1,2,4,7] and B = [1,3,4,5,6,8], then merged list C will be [1,1,2,3,4,4,5,6,7,8]

We will solve this using recursion. So the function will work like below −

  • Suppose the lists A and B of function merge()
  • if A is empty, then return B, if B is empty, then return A
  • if value in A <= value in B, then = merge(, B) and return A
  • otherwise, then = merge(A, and return B

Let us see the implementation to get a better understanding

Example (Python)

 Live Demo

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


head1 = make_list([1,2,4,7])
head2 = make_list([1,3,4,5,6,8])


[1, 1, 2, 3, 4, 4, 5, 6, 7, 8, ]
Published on 08-Jan-2020 15:09:19