Program to merge in between linked lists in Python


Suppose we have two linked lists L1 and L2 of length m and n respectively, we also have two positions a and b. We have to remove nodes from L1 from a-th node to node b-th node and merge L2 in between.

So, if the input is like L1 = [1,5,6,7,1,6,3,9,12] L2 = [5,7,1,6] a = 3 b = 6, then the output will be [1, 5, 6, 5, 7, 1, 6, 9, 12]

To solve this, we will follow these steps −

  • head2 := L2, temp := L2
  • while temp has next node, do
    • temp := next of temp
  • tail2 := temp
  • count := 0
  • temp := L1
  • end1 := null, start3 := null
  • while temp is not null, do
    • if count is same as a-1, then
      • end1 := temp
    • if count is same as b+1, then
      • start3 := temp
      • come out from loop
    • temp := next of temp
    • count := count + 1
  • next of end1 := head2
  • next of tail2 := start3
  • return L1

Example

Let us see the following implementation to get better understanding −

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 solve(L1, L2, a, b):
   head2 = temp = L2
   while temp.next:
      temp = temp.next
   tail2 = temp

   count = 0
   temp = L1
   end1, start3 = None, None
   while temp:
      if count == a-1:
         end1 = temp
      if count == b+1:
         start3 = temp
         break
      temp = temp.next
      count += 1

   end1.next = head2
   tail2.next = start3
   return L1

L1 = [1,5,6,7,1,6,3,9,12]
L2 = [5,7,1,6]
a = 3
b = 6
print_list(solve(make_list(L1), make_list(L2), a, b))

Input

[1,5,6,7,1,6,3,9,12], [5,7,1,6], 3, 6

Output

[1, 5, 6, 5, 7, 1, 6, 9, 12, ]

Updated on: 05-Oct-2021

738 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements