Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer.
Explanation: After inserting nodes of head2 alternately into head1, the modified lists become 10 -> 6 -> 9 -> 1 and 2 -> 3 -> 4 -> 5, as the remaining nodes of head2 cannot be inserted.
Explanation: After inserting nodes of head2 alternately into head1, the merged list becomes 1 -> 4 -> 2 -> 5 -> 3 -> 6, and head2 becomes empty as all its nodes are used.
The idea is to first store all nodes of the second linked list in an array. Then, traverse the first list and insert nodes from the array one by one at alternate positions.
Traverse the second list and store its nodes in an array.
Traverse the first list.
Insert one stored node after every node of the first list.
If nodes of the second list remain, keep them as the second list.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to print linked listvoidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data;if(curr->next!=nullptr)cout<<" -> ";curr=curr->next;}cout<<endl;}// Function to merge two linked listsvector<Node*>mergeList(Node*head1,Node*head2){// Vector to store nodes of second listvector<Node*>arr;Node*temp=head2;// Store all nodes of second listwhile(temp!=nullptr){arr.push_back(temp);temp=temp->next;}Node*curr1=head1;inti=0;// Insert nodes at alternate positionswhile(curr1!=nullptr&&i<arr.size()){// Store next pointersNode*next1=curr1->next;Node*next2=arr[i]->next;// Insert node from second listcurr1->next=arr[i];arr[i]->next=next1;// Move to next nodecurr1=next1;// Update remaining second listarr[i]=next2;i++;}// Remaining nodes of second listNode*rem=nullptr;if(i<arr.size())rem=arr[i];return{head1,rem};}// Driver Codeintmain(){// Creating first linked list: 10->9Node*head1=newNode(10);head1->next=newNode(9);// Creating second linked list: 6->1->2->3->4->5Node*head2=newNode(6);head2->next=newNode(1);head2->next->next=newNode(2);head2->next->next->next=newNode(3);head2->next->next->next->next=newNode(4);head2->next->next->next->next->next=newNode(5);vector<Node*>ans=mergeList(head1,head2);cout<<"head1: ";printList(ans[0]);cout<<"head2: ";printList(ans[1]);return0;}
Java
// Java program to merge a linked list into another// at alternate positions using extra spaceimportjava.util.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to print linked liststaticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data);if(curr.next!=null)System.out.print(" -> ");curr=curr.next;}System.out.println();}// Function to merge two linked listsstaticNode[]mergeList(Nodehead1,Nodehead2){// ArrayList to store nodes of second listArrayList<Node>arr=newArrayList<>();Nodetemp=head2;// Store all nodes of second listwhile(temp!=null){arr.add(temp);temp=temp.next;}Nodecurr1=head1;inti=0;// Insert nodes at alternate positionswhile(curr1!=null&&i<arr.size()){// Store next pointersNodenext1=curr1.next;Nodenext2=arr.get(i).next;// Insert node from second listcurr1.next=arr.get(i);arr.get(i).next=next1;// Move to next nodecurr1=next1;// Update remaining second listarr.set(i,next2);i++;}// Remaining nodes of second listNoderem=null;if(i<arr.size())rem=arr.get(i);returnnewNode[]{head1,rem};}// Driver Codepublicstaticvoidmain(String[]args){// Creating first linked list: 10->9Nodehead1=newNode(10);head1.next=newNode(9);// Creating second linked list: 6->1->2->3->4->5Nodehead2=newNode(6);head2.next=newNode(1);head2.next.next=newNode(2);head2.next.next.next=newNode(3);head2.next.next.next.next=newNode(4);head2.next.next.next.next.next=newNode(5);Node[]ans=mergeList(head1,head2);System.out.print("head1: ");printList(ans[0]);System.out.print("head2: ");printList(ans[1]);}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# Function to print linked listdefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end="")ifcurr.nextisnotNone:print(" -> ",end="")curr=curr.nextprint()# Function to merge two linked listsdefmerge_list(head1,head2):# List to store nodes of second listarr=[]temp=head2# Store all nodes of second listwhiletempisnotNone:arr.append(temp)temp=temp.nextcurr1=head1i=0# Insert nodes at alternate positionswhilecurr1isnotNoneandi<len(arr):# Store next pointersnext1=curr1.nextnext2=arr[i].next# Insert node from second listcurr1.next=arr[i]arr[i].next=next1# Move to next nodecurr1=next1# Update remaining second listarr[i]=next2i+=1# Remaining nodes of second listrem=Noneifi<len(arr):rem=arr[i]return[head1,rem]# Driver Codeif__name__=="__main__":# Creating first linked list: 10->9head1=Node(10)head1.next=Node(9)# Creating second linked list: 6->1->2->3->4->5head2=Node(6)head2.next=Node(1)head2.next.next=Node(2)head2.next.next.next=Node(3)head2.next.next.next.next=Node(4)head2.next.next.next.next.next=Node(5)ans=merge_list(head1,head2)print("head1: ",end="")print_list(ans[0])print("head2: ",end="")print_list(ans[1])
C#
// C# program to merge a linked list into another// at alternate positions using extra spaceusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to print linked liststaticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data);if(curr.next!=null)Console.Write(" -> ");curr=curr.next;}Console.WriteLine();}// Function to merge two linked listsstaticNode[]MergeList(Nodehead1,Nodehead2){// List to store nodes of second listList<Node>arr=newList<Node>();Nodetemp=head2;// Store all nodes of second listwhile(temp!=null){arr.Add(temp);temp=temp.next;}Nodecurr1=head1;inti=0;// Insert nodes at alternate positionswhile(curr1!=null&&i<arr.Count){// Store next pointersNodenext1=curr1.next;Nodenext2=arr[i].next;// Insert node from second listcurr1.next=arr[i];arr[i].next=next1;// Move to next nodecurr1=next1;// Update remaining second listarr[i]=next2;i++;}// Remaining nodes of second listNoderem=null;if(i<arr.Count)rem=arr[i];returnnewNode[]{head1,rem};}// Driver CodestaticvoidMain(){// Creating first linked list: 10->9Nodehead1=newNode(10);head1.next=newNode(9);// Creating second linked list: 6->1->2->3->4->5Nodehead2=newNode(6);head2.next=newNode(1);head2.next.next=newNode(2);head2.next.next.next=newNode(3);head2.next.next.next.next=newNode(4);head2.next.next.next.next.next=newNode(5);Node[]ans=MergeList(head1,head2);Console.Write("head1: ");PrintList(ans[0]);Console.Write("head2: ");PrintList(ans[1]);}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to print linked listfunctionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data);if(curr.next!==null){process.stdout.write(' -> ');}curr=curr.next;}console.log('\n');}// Function to merge two linked listsfunctionmergeList(head1,head2){// Array to store nodes of second listletarr=[];lettemp=head2;// Store all nodes of second listwhile(temp!==null){arr.push(temp);temp=temp.next;}letcurr1=head1;leti=0;// Insert nodes at alternate positionswhile(curr1!==null&&i<arr.length){// Store next pointersletnext1=curr1.next;letnext2=arr[i].next;// Insert node from second listcurr1.next=arr[i];arr[i].next=next1;// Move to next nodecurr1=next1;// Update remaining second listarr[i]=next2;i++;}// Remaining nodes of second listletrem=null;if(i<arr.length){rem=arr[i];}return[head1,rem];}// Driver Code// Creating first linked list: 10->9lethead1=newNode(10);head1.next=newNode(9);// Creating second linked list: 6->1->2->3->4->5lethead2=newNode(6);head2.next=newNode(1);head2.next.next=newNode(2);head2.next.next.next=newNode(3);head2.next.next.next.next=newNode(4);head2.next.next.next.next.next=newNode(5);letans=mergeList(head1,head2);console.log('head1: ');printList(ans[0]);console.log('head2: ');printList(ans[1]);
Output
head1: 10 -> 6 -> 9 -> 1
head2: 2 -> 3 -> 4 -> 5
Time Complexity: O(n1 + n2), traversing second linked list and storing nodes in vector takes O(n2) time, and traversing first linked list for insertion takes O(min(n1, n2)) time. Auxiliary Space: O(n2)
Using Iterative Method – O(min(n1, n2)) Time O(1) Space
The idea is to start traversing from the beginning of both lists. For each step, take a node from the second list and insert it after a node from the first list. This process continues until we reach the end of one or both lists. If the second list is longer, remaining nodes will be kept as it is second list.
Initialize two pointers to traverse the first and second linked lists.
Traverse both linked lists simultaneously until one of them becomes empty.
For every node of the first list, store the next nodes of both lists before changing links.
Insert the current node of the second list after the current node of the first list.
Move both pointers forward and continue the process. Remaining nodes of the second list stay unchanged.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to print linked listvoidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data;if(curr->next!=nullptr)cout<<" -> ";curr=curr->next;}cout<<endl;}// Function to merge two linked listsvector<Node*>mergeList(Node*head1,Node*head2){// Initialize pointers to traverse the two listsNode*curr1=head1;Node*curr2=head2;// Traverse both lists and merge themwhile(curr1!=nullptr&&curr2!=nullptr){// Save the next nodes of the current// nodes in both listsNode*ptr1=curr1->next;Node*ptr2=curr2->next;// Insert the current node from second list// after the current node from first listcurr2->next=curr1->next;curr1->next=curr2;// Update the pointers for next iterationcurr1=ptr1;curr2=ptr2;}return{head1,curr2};}// Driver Codeintmain(){// Creating first linked list: 10->9Node*head1=newNode(10);head1->next=newNode(9);// Creating second linked list: 6->1->2->3->4->5Node*head2=newNode(6);head2->next=newNode(1);head2->next->next=newNode(2);head2->next->next->next=newNode(3);head2->next->next->next->next=newNode(4);head2->next->next->next->next->next=newNode(5);vector<Node*>ans=mergeList(head1,head2);cout<<"head1: ";printList(ans[0]);cout<<"head2: ";printList(ans[1]);return0;}
Java
classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGfG{// Function to print linked listpublicstaticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data);if(curr.next!=null)System.out.print(" -> ");curr=curr.next;}System.out.println();}// Function to merge two linked listspublicstaticNode[]mergeList(Nodehead1,Nodehead2){// Initialize pointers to traverse the two listsNodecurr1=head1;Nodecurr2=head2;// Traverse both lists and merge themwhile(curr1!=null&&curr2!=null){// Save the next nodesNodeptr1=curr1.next;Nodeptr2=curr2.next;// Insert node from second listcurr2.next=curr1.next;curr1.next=curr2;// Move pointerscurr1=ptr1;curr2=ptr2;}returnnewNode[]{head1,curr2};}// Driver Codepublicstaticvoidmain(String[]args){// Creating first linked list: 10->9Nodehead1=newNode(10);head1.next=newNode(9);// Creating second linked list: 6->1->2->3->4->5Nodehead2=newNode(6);head2.next=newNode(1);head2.next.next=newNode(2);head2.next.next.next=newNode(3);head2.next.next.next.next=newNode(4);head2.next.next.next.next.next=newNode(5);Node[]ans=mergeList(head1,head2);System.out.print("head1: ");printList(ans[0]);System.out.print("head2: ");printList(ans[1]);}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# Function to print linked listdefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end="")ifcurr.nextisnotNone:print(" -> ",end="")curr=curr.nextprint()# Function to merge two linked listsdefmerge_list(head1,head2):# Initialize pointers to traverse the two listscurr1=head1curr2=head2# Traverse both lists and merge themwhilecurr1isnotNoneandcurr2isnotNone:# Save the next nodes of the current# nodes in both listsptr1=curr1.nextptr2=curr2.next# Insert the current node from second list# after the current node from first listcurr2.next=curr1.nextcurr1.next=curr2# Update the pointers for next iterationcurr1=ptr1curr2=ptr2return[head1,curr2]# Driver Codeif__name__=="__main__":# Creating first linked list: 10->9head1=Node(10)head1.next=Node(9)# Creating second linked list: 6->1->2->3->4->5head2=Node(6)head2.next=Node(1)head2.next.next=Node(2)head2.next.next.next=Node(3)head2.next.next.next.next=Node(4)head2.next.next.next.next.next=Node(5)ans=merge_list(head1,head2)print("head1: ",end="")print_list(ans[0])print("head2: ",end="")print_list(ans[1])
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGfG{// Function to print linked listpublicstaticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data);if(curr.next!=null)Console.Write(" -> ");curr=curr.next;}Console.WriteLine();}// Function to merge two linked listspublicstaticList<Node>mergeList(Nodehead1,Nodehead2){// Initialize pointers to traverse the two listsNodecurr1=head1;Nodecurr2=head2;// Traverse both lists and merge themwhile(curr1!=null&&curr2!=null){// Save the next nodesNodeptr1=curr1.next;Nodeptr2=curr2.next;// Insert node from second listcurr2.next=curr1.next;curr1.next=curr2;// Move pointerscurr1=ptr1;curr2=ptr2;}returnnewList<Node>{head1,curr2};}// Driver CodepublicstaticvoidMain(){// Creating first linked list: 10->9Nodehead1=newNode(10);head1.next=newNode(9);// Creating second linked list: 6->1->2->3->4->5Nodehead2=newNode(6);head2.next=newNode(1);head2.next.next=newNode(2);head2.next.next.next=newNode(3);head2.next.next.next.next=newNode(4);head2.next.next.next.next.next=newNode(5);List<Node>ans=mergeList(head1,head2);Console.Write("head1: ");printList(ans[0]);Console.Write("head2: ");printList(ans[1]);}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to print linked listfunctionprintList(head){letcurr=head;while(curr!==null){process.stdout.write(curr.data.toString());if(curr.next!==null)process.stdout.write(" -> ");curr=curr.next;}console.log();}// Function to merge two linked listsfunctionmergeList(head1,head2){// Initialize pointers to traverse the two listsletcurr1=head1;letcurr2=head2;// Traverse both lists and merge themwhile(curr1!==null&&curr2!==null){// Save the next nodesletptr1=curr1.next;letptr2=curr2.next;// Insert node from second listcurr2.next=curr1.next;curr1.next=curr2;// Move pointerscurr1=ptr1;curr2=ptr2;}return[head1,curr2];}// Driver Code// Creating first linked list: 10->9lethead1=newNode(10);head1.next=newNode(9);// Creating second linked list: 6->1->2->3->4->5lethead2=newNode(6);head2.next=newNode(1);head2.next.next=newNode(2);head2.next.next.next=newNode(3);head2.next.next.next.next=newNode(4);head2.next.next.next.next.next=newNode(5);letans=mergeList(head1,head2);process.stdout.write("head1: ");printList(ans[0]);process.stdout.write("head2: ");printList(ans[1]);
Output
head1: 10 -> 6 -> 9 -> 1
head2: 2 -> 3 -> 4 -> 5
Time Complexity: O(min(n1, n2)), where n1 and n2 represents the length of the given two linked lists. Auxiliary Space: O(1).