Merge a linked list into another linked list at alternate positions
Last Updated : 13 Sep, 2024
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.
Using Iterative Method – O(n) Time and 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.
C++
// C++ program to merge a linked list into another at// alternate positions#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};voidprintList(Node*head){Node*curr=head;while(curr!=NULL){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}// Function to merge two linked listsvector<Node*>merge(Node*head1,Node*head2){// Initialize pointers to traverse the two listsNode*curr1=head1;Node*curr2=head2;// Traverse both lists and merge themwhile(curr1!=NULL&&curr2!=NULL){// Save the next nodes of the current // nodes in both listsNode*ptr1=curr1->next;Node*ptr2=curr2->next;// Insert the current node from the second list// after the current node from the first listcurr2->next=curr1->next;curr1->next=curr2;// Update the pointers for the next iterationcurr1=ptr1;curr2=ptr2;}return{head1,curr2};}intmain(){// Creating first linked list 1->2->3Node*head1=newNode(1);head1->next=newNode(2);head1->next->next=newNode(3);// crating second listed list 4->5->6->7->8Node*head2=newNode(4);head2->next=newNode(5);head2->next->next=newNode(6);head2->next->next->next=newNode(7);head2->next->next->next->next=newNode(8);// Store first and second head points in arrayvector<Node*>ar=merge(head1,head2);printList(ar[0]);printList(ar[1]);return0;}
C
// C program to merge a linked list into another at// alternate positions#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}// Function to merge two linked listsstructNode*merge(structNode*head1,structNode*head2){structNode*curr1=head1;structNode*curr2=head2;structNode*next1,*next2;// Traverse both lists and merge themwhile(curr1!=NULL&&curr2!=NULL){// Save the next nodes of the current // nodes in both listsnext1=curr1->next;next2=curr2->next;// Insert the current node from the second list// after the current node from the first listcurr2->next=curr1->next;curr1->next=curr2;// Update the pointers for the next iterationcurr1=next1;curr2=next2;}// Return the remaining part of the second listreturncurr2;}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){// Creating the first linked list: 1->2->3structNode*head1=createNode(1);head1->next=createNode(2);head1->next->next=createNode(3);// Creating the second linked list: 4->5->6->7->8structNode*head2=createNode(4);head2->next=createNode(5);head2->next->next=createNode(6);head2->next->next->next=createNode(7);head2->next->next->next->next=createNode(8);structNode*remaining=merge(head1,head2);// Print merged list and remaining listprintList(head1);printList(remaining);return0;}
Java
// Java program to merge a linked list into another at// alternate positionsimportjava.util.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to print a linked liststaticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}// Function to merge two linked listsstaticList<Node>merge(Nodehead1,Nodehead2){// Initialize pointers to traverse the two listsNodetemp1=head1;Nodetemp2=head2;// Traverse both lists and merge themwhile(temp1!=null&&temp2!=null){// Save the next nodes of the current nodes in// both listsNodeptr1=temp1.next;Nodeptr2=temp2.next;// Insert the current node from the second list// after the current node from the first listtemp2.next=temp1.next;temp1.next=temp2;// Update the pointers for the next iterationtemp1=ptr1;temp2=ptr2;}returnArrays.asList(head1,temp2);}publicstaticvoidmain(String[]args){// Creating first linked list 1->2->3Nodehead1=newNode(1);head1.next=newNode(2);head1.next.next=newNode(3);// Creating second linked list 4->5->6->7->8Nodehead2=newNode(4);head2.next=newNode(5);head2.next.next=newNode(6);head2.next.next.next=newNode(7);head2.next.next.next.next=newNode(8);// Store first and second head points in arrayList<Node>ar=merge(head1,head2);printList(ar.get(0));printList(ar.get(1));}}
Python
# Python program to merge a linked list into another at# alternate positionsclassNode:def__init__(self,x):self.data=xself.next=NonedefprintList(head):curr=headwhilecurr:print(curr.data,end=" ")curr=curr.nextprint()# Function to merge two linked listsdefmerge(head1,head2):# Initialize pointers to traverse the two liststemp1=head1temp2=head2# Traverse both lists and merge themwhiletemp1isnotNoneandtemp2isnotNone:# Save the next nodes of the current# nodes in both listsptr1=temp1.nextptr2=temp2.next# Insert the current node from the second list# after the current node from the first listtemp2.next=temp1.nexttemp1.next=temp2# Update the pointers for the next iterationtemp1=ptr1temp2=ptr2return[head1,temp2]if__name__=="__main__":# Creating first linked list 1->2->3head1=Node(1)head1.next=Node(2)head1.next.next=Node(3)# Creating second linked list 4->5->6->7->8head2=Node(4)head2.next=Node(5)head2.next.next=Node(6)head2.next.next.next=Node(7)head2.next.next.next.next=Node(8)# Store first and second head points in arrayar=merge(head1,head2)printList(ar[0])printList(ar[1])
C#
// C# program to merge a linked list into// another at alternate positionsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}// Function to merge two linked listsstaticList<Node>Merge(Nodehead1,Nodehead2){// Initialize pointers to traverse the two listsNodetemp1=head1;Nodetemp2=head2;// Traverse both lists and merge themwhile(temp1!=null&&temp2!=null){// Save the next nodes of the current nodes in// both listsNodeptr1=temp1.next;Nodeptr2=temp2.next;// Insert the current node from the second list// after the current node from the first listtemp2.next=temp1.next;temp1.next=temp2;// Update the pointers for the next iterationtemp1=ptr1;temp2=ptr2;}returnnewList<Node>{head1,temp2};}staticvoidMain(string[]args){// Creating first linked list 1->2->3Nodehead1=newNode(1);head1.next=newNode(2);head1.next.next=newNode(3);// Creating second linked list 4->5->6->7->8Nodehead2=newNode(4);head2.next=newNode(5);head2.next.next=newNode(6);head2.next.next.next=newNode(7);head2.next.next.next.next=newNode(8);// Store first and second head points in arrayList<Node>ar=Merge(head1,head2);PrintList(ar[0]);PrintList(ar[1]);}}
JavaScript
// Javascript program to merge a linked list// into another at alternate positionsclassNode{constructor(x){this.data=x;this.next=null;}}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data+" ");curr=curr.next;}console.log();}// Function to merge two linked listsfunctionmerge(head1,head2){// Initialize pointers to traverse the two listslettemp1=head1;lettemp2=head2;// Traverse both lists and merge themwhile(temp1!==null&&temp2!==null){// Save the next nodes of the current nodes in both// listsletptr1=temp1.next;letptr2=temp2.next;// Insert the current node from the second list// after the current node from the first listtemp2.next=temp1.next;temp1.next=temp2;// Update the pointers for the next iterationtemp1=ptr1;temp2=ptr2;}return[head1,temp2];}// Creating first linked list 1->2->3lethead1=newNode(1);head1.next=newNode(2);head1.next.next=newNode(3);// Creating second linked list 4->5->6->7->8lethead2=newNode(4);head2.next=newNode(5);head2.next.next=newNode(6);head2.next.next.next=newNode(7);head2.next.next.next.next=newNode(8);// Store first and second head points in arrayletar=merge(head1,head2);printList(ar[0]);printList(ar[1]);
Output
1 4 2 5 3 6
7 8
Time Complexity: O(min(n1, n2)), where n1 and n2 represents the length of the given two linked lists. Auxiliary Space: O(1).