Given two sorted linked lists head1 and head2, merge them into a single sorted linked list and return the head of the merged list. The merged list should contain all the nodes from both linked lists in sorted order.
[Naive Approach] By Using Array - O((n+m) × log(n+m)) Time and O(n+m) Space
The idea is to use an array to store all the node data from both linked lists, sort the array, and then construct the resultant sorted linked list from the array elements.
C++
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*sortedMerge(Node*head1,Node*head2){vector<int>arr;// pushing the values of the first linked listwhile(head1!=nullptr){arr.push_back(head1->data);head1=head1->next;}// pushing the values of the second linked listwhile(head2!=nullptr){arr.push_back(head2->data);head2=head2->next;}// sorting the vectorsort(arr.begin(),arr.end());// creating a new list with sorted valuesNode*dummy=newNode(-1);Node*curr=dummy;for(inti=0;i<arr.size();i++){curr->next=newNode(arr[i]);curr=curr->next;}returndummy->next;}voidprintList(Node*curr){while(curr!=nullptr){cout<<curr->data;if(curr->next!=nullptr)cout<<" -> ";curr=curr->next;}cout<<endl;}intmain(){Node*head1=newNode(5);head1->next=newNode(10);head1->next->next=newNode(15);head1->next->next->next=newNode(40);Node*head2=newNode(2);head2->next=newNode(3);head2->next->next=newNode(20);Node*res=sortedMerge(head1,head2);printList(res);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->next=NULL;returnnode;}structNode*sortedMerge(structNode*head1,structNode*head2){intarr[10000];intsize=0;// pushing the values of the first linked listwhile(head1!=NULL){arr[size++]=head1->data;head1=head1->next;}// pushing the values of the second linked listwhile(head2!=NULL){arr[size++]=head2->data;head2=head2->next;}// sorting the arrayfor(inti=0;i<size-1;i++){for(intj=i+1;j<size;j++){if(arr[i]>arr[j]){inttemp=arr[i];arr[i]=arr[j];arr[j]=temp;}}}// creating a new list with sorted valuesstructNode*dummy=createNode(-1);structNode*curr=dummy;for(inti=0;i<size;i++){curr->next=createNode(arr[i]);curr=curr->next;}returndummy->next;}voidprintList(structNode*curr){while(curr!=NULL){printf("%d",curr->data);if(curr->next!=NULL)printf(" -> ");curr=curr->next;}printf("\n");}intmain(){structNode*head1=createNode(5);head1->next=createNode(10);head1->next->next=createNode(15);head1->next->next->next=createNode(40);structNode*head2=createNode(2);head2->next=createNode(3);head2->next->next=createNode(20);structNode*res=sortedMerge(head1,head2);printList(res);return0;}
Java
importjava.util.ArrayList;importjava.util.Collections;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticNodesortedMerge(Nodehead1,Nodehead2){ArrayList<Integer>arr=newArrayList<>();// pushing the values of the first linked listwhile(head1!=null){arr.add(head1.data);head1=head1.next;}// pushing the values of the second linked listwhile(head2!=null){arr.add(head2.data);head2=head2.next;}// sorting the listCollections.sort(arr);// creating a new list with sorted valuesNodedummy=newNode(-1);Nodecurr=dummy;for(inti=0;i<arr.size();i++){curr.next=newNode(arr.get(i));curr=curr.next;}returndummy.next;}staticvoidprintList(Nodecurr){while(curr!=null){System.out.print(curr.data);if(curr.next!=null){System.out.print(" -> ");}curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
Python
classNode:def__init__(self,x):self.data=xself.next=NonedefsortedMerge(head1,head2):arr=[]# pushing the values of the first linked listwhilehead1isnotNone:arr.append(head1.data)head1=head1.next# pushing the values of the second linked listwhilehead2isnotNone:arr.append(head2.data)head2=head2.next# sorting the listarr.sort()# creating a new list with sorted valuesdummy=Node(-1)curr=dummyforvalueinarr:curr.next=Node(value)curr=curr.nextreturndummy.nextdefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.nextisnotNone:print(" -> ",end="")node=node.nextprint()if__name__=="__main__":head1=Node(5)head1.next=Node(10)head1.next.next=Node(15)head1.next.next.next=Node(40)head2=Node(2)head2.next=Node(3)head2.next.next=Node(20)res=sortedMerge(head1,head2)printList(res)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodesortedMerge(Nodehead1,Nodehead2){List<int>arr=newList<int>();// pushing the values of the first linked listwhile(head1!=null){arr.Add(head1.data);head1=head1.next;}// pushing the values of the second linked listwhile(head2!=null){arr.Add(head2.data);head2=head2.next;}// sorting the listarr.Sort();// creating a new list with sorted valuesNodedummy=newNode(-1);Nodecurr=dummy;foreach(intvalueinarr){curr.next=newNode(value);curr=curr.next;}returndummy.next;}staticvoidprintList(Nodecurr){while(curr!=null){Console.Write(curr.data);if(curr.next!=null){Console.Write(" -> ");}curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionsortedMerge(head1,head2){letarr=[];// pushing the values of the first linked listwhile(head1!==null){arr.push(head1.data);head1=head1.next;}// pushing the values of the second linked listwhile(head2!==null){arr.push(head2.data);head2=head2.next;}// sorting the arrayarr.sort((x,y)=>x-y);// creating a new list with sorted valuesletdummy=newNode(-1);letcurr=dummy;for(letvalueofarr){curr.next=newNode(value);curr=curr.next;}returndummy.next;}functionprintList(node){while(node!==null){process.stdout.write(node.data.toString());if(node.next!==null){process.stdout.write(" -> ");}node=node.next;}}lethead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);lethead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);letres=sortedMerge(head1,head2);printList(res);
Output
2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40
[Better Approach] Using Recursive Merge - O(n+m) Time and O(n+m) Space
Since both linked lists are sorted, compare the data of the current nodes of both lists. The node with the smaller value is placed first, and the remaining nodes are merged recursively.
If head1 is nullptr, return head2.
If head2 is nullptr, return head1.
If head1->data <= head2->data, recursively merge head1->next and head2, and link the result with head1.
Otherwise, recursively merge head1 and head2->next, and link the result with head2.
Return the first node of the merged list.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*sortedMerge(Node*head1,Node*head2){// base casesif(head1==nullptr)returnhead2;if(head2==nullptr)returnhead1;// recursive merging based on smaller valueif(head1->data<=head2->data){head1->next=sortedMerge(head1->next,head2);returnhead1;}else{head2->next=sortedMerge(head1,head2->next);returnhead2;}}voidprintList(Node*curr){while(curr!=nullptr){cout<<curr->data;if(curr->next!=nullptr)cout<<" -> ";curr=curr->next;}cout<<endl;}intmain(){Node*head1=newNode(5);head1->next=newNode(10);head1->next->next=newNode(15);head1->next->next->next=newNode(40);Node*head2=newNode(2);head2->next=newNode(3);head2->next->next=newNode(20);Node*res=sortedMerge(head1,head2);printList(res);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*sortedMerge(structNode*head1,structNode*head2){// base casesif(head1==NULL)returnhead2;if(head2==NULL)returnhead1;// recursive merging based on smaller valueif(head1->data<=head2->data){head1->next=sortedMerge(head1->next,head2);returnhead1;}else{head2->next=sortedMerge(head1,head2->next);returnhead2;}}voidprintList(structNode*curr){while(curr!=NULL){printf("%d",curr->data);if(curr->next!=NULL){printf(" -> ");}curr=curr->next;}printf("\n");}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){structNode*head1=createNode(5);head1->next=createNode(10);head1->next->next=createNode(15);head1->next->next->next=createNode(40);structNode*head2=createNode(2);head2->next=createNode(3);head2->next->next=createNode(20);structNode*res=sortedMerge(head1,head2);printList(res);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticNodesortedMerge(Nodehead1,Nodehead2){// base casesif(head1==null)returnhead2;if(head2==null)returnhead1;// recursive merging based on smaller valueif(head1.data<=head2.data){head1.next=sortedMerge(head1.next,head2);returnhead1;}else{head2.next=sortedMerge(head1,head2.next);returnhead2;}}staticvoidprintList(Nodecurr){while(curr!=null){System.out.print(curr.data);if(curr.next!=null)System.out.print(" -> ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
Python
classNode:def__init__(self,x):self.data=xself.next=NonedefsortedMerge(head1,head2):# base casesifhead1isNone:returnhead2ifhead2isNone:returnhead1# recursive merging based on smaller valueifhead1.data<=head2.data:head1.next=sortedMerge(head1.next,head2)returnhead1else:head2.next=sortedMerge(head1,head2.next)returnhead2defprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.nextisnotNone:print(" -> ",end="")node=node.nextprint()if__name__=="__main__":head1=Node(5)head1.next=Node(10)head1.next.next=Node(15)head1.next.next.next=Node(40)head2=Node(2)head2.next=Node(3)head2.next.next=Node(20)res=sortedMerge(head1,head2)printList(res)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodesortedMerge(Nodehead1,Nodehead2){// base casesif(head1==null)returnhead2;if(head2==null)returnhead1;// recursive merging based on smaller valueif(head1.data<=head2.data){head1.next=sortedMerge(head1.next,head2);returnhead1;}else{head2.next=sortedMerge(head1,head2.next);returnhead2;}}staticvoidprintList(Nodecurr){while(curr!=null){Console.Write(curr.data);if(curr.next!=null)Console.Write(" -> ");curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionsortedMerge(head1,head2){// base casesif(head1===null)returnhead2;if(head2===null)returnhead1;// recursive merging based on smaller valueif(head1.data<=head2.data){head1.next=sortedMerge(head1.next,head2);returnhead1;}else{head2.next=sortedMerge(head1,head2.next);returnhead2;}}functionprintList(node){while(node!==null){process.stdout.write(node.data.toString());if(node.next!==null){process.stdout.write(" -> ");}node=node.next;}}// Driver Codelethead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);lethead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);letres=sortedMerge(head1,head2);printList(res);
Output
2 -> 3 -> 5 -> 10 -> 15 -> 20 -> 40
[Efficient Approach] Using Iterative Merge - O(n+m) Time and O(1) Space
The idea is to iteratively merge two sorted linked lists using a dummy node to simplify the process. A current pointer tracks the last node of the merged list. We compare the nodes from both lists and append the smaller node to the merged list. Once one list is fully traversed, the remaining nodes from the other list are appended. The merged list is returned starting from the node after the dummy node.
Working:
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*sortedMerge(Node*head1,Node*head2){// create a dummy node to simplify // the merging processNode*dummy=newNode(-1);Node*curr=dummy;// iterate through both linked listswhile(head1!=nullptr&&head2!=nullptr){// add the smaller node to the merged listif(head1->data<=head2->data){curr->next=head1;head1=head1->next;}else{curr->next=head2;head2=head2->next;}curr=curr->next;}// if any list is left, append it to// the merged listif(head1!=nullptr){curr->next=head1;}else{curr->next=head2;}// return the merged list starting// from the next of dummy nodereturndummy->next;}voidprintList(Node*head){while(head!=nullptr){cout<<head->data;if(head->next!=nullptr)cout<<" -> ";head=head->next;}cout<<endl;}intmain(){Node*head1=newNode(5);head1->next=newNode(10);head1->next->next=newNode(15);head1->next->next->next=newNode(40);Node*head2=newNode(2);head2->next=newNode(3);head2->next->next=newNode(20);Node*res=sortedMerge(head1,head2);printList(res);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata);structNode*sortedMerge(structNode*head1,structNode*head2){// create a dummy node to simplify// the merging processstructNode*dummy=createNode(-1);structNode*curr=dummy;// iterate through both linked listswhile(head1!=NULL&&head2!=NULL){// add the smaller node to the merged listif(head1->data<=head2->data){curr->next=head1;head1=head1->next;}else{curr->next=head2;head2=head2->next;}curr=curr->next;}// if any list is left, append it to // the merged listif(head1!=NULL){curr->next=head1;}else{curr->next=head2;}// return the merged list starting // from the next of dummy nodereturndummy->next;}voidprintList(structNode*head){while(head!=NULL){printf("%d",head->data);if(head->next!=NULL){printf(" -> ");}head=head->next;}printf("\n");}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){structNode*head1=createNode(5);head1->next=createNode(10);head1->next->next=createNode(15);head1->next->next->next=createNode(40);structNode*head2=createNode(2);head2->next=createNode(3);head2->next->next=createNode(20);structNode*res=sortedMerge(head1,head2);printList(res);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticNodesortedMerge(Nodehead1,Nodehead2){// create a dummy node to simplify // the merging processNodedummy=newNode(-1);Nodecurr=dummy;// iterate through both linked listswhile(head1!=null&&head2!=null){// add the smaller node to the merged listif(head1.data<=head2.data){curr.next=head1;head1=head1.next;}else{curr.next=head2;head2=head2.next;}curr=curr.next;}// if any list is left, append it to // the merged listif(head1!=null){curr.next=head1;}else{curr.next=head2;}// return the merged list starting from // the next of dummy nodereturndummy.next;}staticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" -> ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
Python
classNode:def__init__(self,x):self.data=xself.next=NonedefsortedMerge(head1,head2):# create a dummy node to simplify # the merging processdummy=Node(-1)curr=dummy# iterate through both linked listswhilehead1isnotNoneandhead2isnotNone:# add the smaller node to the merged listifhead1.data<=head2.data:curr.next=head1head1=head1.nextelse:curr.next=head2head2=head2.nextcurr=curr.next# if any list is left, append it to the merged listifhead1isnotNone:curr.next=head1else:curr.next=head2# return the merged list starting from # the next of dummy nodereturndummy.nextdefprintList(head):whileheadisnotNone:ifhead.nextisnotNone:print(head.data,end=" -> ")else:print(head.data)head=head.nextif__name__=="__main__":head1=Node(5)head1.next=Node(10)head1.next.next=Node(15)head1.next.next.next=Node(40)head2=Node(2)head2.next=Node(3)head2.next.next=Node(20)res=sortedMerge(head1,head2)printList(res)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodesortedMerge(Nodehead1,Nodehead2){// create a dummy node to simplify the // merging processNodedummy=newNode(-1);Nodecurr=dummy;// iterate through both linked listswhile(head1!=null&&head2!=null){// add the smaller node to the merged listif(head1.data<=head2.data){curr.next=head1;head1=head1.next;}else{curr.next=head2;head2=head2.next;}curr=curr.next;}// if any list is left, append it to the // merged listif(head1!=null){curr.next=head1;}else{curr.next=head2;}// return the merged list starting from // the next of dummy nodereturndummy.next;}staticvoidprintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" -> ");head=head.next;}Console.WriteLine();}staticvoidMain(string[]args){Nodehead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);Nodehead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);Noderes=sortedMerge(head1,head2);printList(res);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionsortedMerge(head1,head2){// create a dummy node to simplify the merging processletdummy=newNode(-1);letcurr=dummy;// iterate through both linked listswhile(head1!==null&&head2!==null){// add the smaller node to the merged listif(head1.data<=head2.data){curr.next=head1;head1=head1.next;}else{curr.next=head2;head2=head2.next;}curr=curr.next;}// if any list is left, append it// to the merged listif(head1!==null){curr.next=head1;}else{curr.next=head2;}// return the merged list starting from// the next of dummy nodereturndummy.next;}functionprintList(head){letresult="";while(head!==null){result+=head.data;if(head.next!==null){result+=" -> ";}head=head.next;}console.log(result);}// Driver codelethead1=newNode(5);head1.next=newNode(10);head1.next.next=newNode(15);head1.next.next.next=newNode(40);lethead2=newNode(2);head2.next=newNode(3);head2.next.next=newNode(20);letres=sortedMerge(head1,head2);printList(res);