Program to find union of two given linked lists in Python


Suppose we have two sorted linked lists L1 and L2, we have to return a new sorted linked list that is the union of the two given lists.

So, if the input is like L1 = [10,20,30,40,50,60,70] L2 = [10,30,50,80,90], then the output will be [10, 20, 30, 40, 50, 60, 70, 80, 90, ]

To solve this, we will follow these steps −

  • Define a function solve() . This will take L1, L2
  • if L1 is empty, then
    • return L2
  • if L2 is empty, then
    • return L1
  • if value of L1 < value of L2, then
    • res := L1
    • next of res := solve(next of L1, L2)
  • otherwise when value of L2 < value of L1, then
    • res := L2
    • next of res := solve(next of L2, L1)
  • otherwise,
    • res := L1
    • next of res := solve(next of L1, next of L2)
  • return res

Let us see the following implementation to get better understanding −

Example

 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 solve(self, L1, L2):
      if not L1:
         return L2
      if not L2:
         return L1
      if L1.val < L2.val:
         res = L1
         res.next = self.solve(L1.next, L2)
      elif L2.val < L1.val:
         res = L2
         res.next = self.solve(L2.next, L1)
      else:
         res = L1
         res.next = self.solve(L1.next, L2.next)
   return res
ob = Solution()
L1 = make_list([10,20,30,40,50,60,70])
L2 = make_list([10,30,50,80,90])
print_list(ob.solve(L1, L2))

Input

[10,20,30,40,50,60,70], [10,30,50,80,90]

Output

[10, 20, 30, 40, 50, 60, 70, 80, 90, ]

Updated on: 19-Nov-2020

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements