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 A.next = merge(A.next, B) and return A
  • otherwise, then B.next = merge(A, B.next) 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
      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(']')
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):
         l1.next = self.mergeTwoLists(l1.next,l2)
         return l1
      else:
         l2.next = self.mergeTwoLists(l1,l2.next)
         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)
print_list(head3)

Input

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

Output

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