The idea is to initialize the result as empty. Now one by one merge every linked list into the resultant list using the idea of merging two sorted linked lists. We always consider the result as first list and other list as second. At the end, we return result.
C++
// C++ program to merge K sorted linked lists#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to merge only 2 listsNode*mergeTwo(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;}// Function to merge K sorted linked listsNode*mergeKLists(vector<Node*>&arr){// Initialize result as emptyNode*res=nullptr;// One by one merge all lists with // res and keep updating resfor(Node*node:arr)res=mergeTwo(res,node);returnres;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}}intmain(){intk=3;vector<Node*>arr(k);arr[0]=newNode(1);arr[0]->next=newNode(3);arr[0]->next->next=newNode(5);arr[0]->next->next->next=newNode(7);arr[1]=newNode(2);arr[1]->next=newNode(4);arr[1]->next->next=newNode(6);arr[1]->next->next->next=newNode(8);arr[2]=newNode(0);arr[2]->next=newNode(9);arr[2]->next->next=newNode(10);arr[2]->next->next->next=newNode(11);Node*head=mergeKLists(arr);printList(head);return0;}
C
// C program to merge K sorted linked lists#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata);// Function to merge only 2 listsstructNode*mergeTwo(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 nodestructNode*merged=dummy->next;free(dummy);returnmerged;}// Function to merge K sorted linked listsstructNode*mergeKLists(structNode**arr,intk){// Initialize result as emptystructNode*res=NULL;// One by one merge all lists with // res and keep updating resfor(inti=0;i<k;i++)res=mergeTwo(res,arr[i]);returnres;}voidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){intk=3;structNode*arr[k];arr[0]=createNode(1);arr[0]->next=createNode(3);arr[0]->next->next=createNode(5);arr[0]->next->next->next=createNode(7);arr[1]=createNode(2);arr[1]->next=createNode(4);arr[1]->next->next=createNode(6);arr[1]->next->next->next=createNode(8);arr[2]=createNode(0);arr[2]->next=createNode(9);arr[2]->next->next=createNode(10);arr[2]->next->next->next=createNode(11);structNode*head=mergeKLists(arr,k);printList(head);return0;}
Java
// Java program to merge K sorted linked listsimportjava.util.List;importjava.util.ArrayList;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to merge only 2 listsstaticNodemergeTwo(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;}// Function to merge K sorted linked listsstaticNodemergeKLists(List<Node>arr){// Initialize result as emptyNoderes=null;// One by one merge all lists with // res and keep updating resfor(Nodenode:arr)res=mergeTwo(res,node);returnres;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}}publicstaticvoidmain(String[]args){List<Node>arr=newArrayList<>();arr.add(newNode(1));arr.get(0).next=newNode(3);arr.get(0).next.next=newNode(5);arr.get(0).next.next.next=newNode(7);arr.add(newNode(2));arr.get(1).next=newNode(4);arr.get(1).next.next=newNode(6);arr.get(1).next.next.next=newNode(8);arr.add(newNode(0));arr.get(2).next=newNode(9);arr.get(2).next.next=newNode(10);arr.get(2).next.next.next=newNode(11);Nodehead=mergeKLists(arr);printList(head);}}
Python
# Python program to merge K sorted linked listsclassNode:def__init__(self,x):self.data=xself.next=None# Function to merge only 2 listsdefmergeTwo(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.next# Function to merge K sorted linked listsdefmergeKLists(arr):# Initialize result as emptyres=None# One by one merge all lists with # res and keep updating resfornodeinarr:res=mergeTwo(res,node)returnresdefprintList(node):whilenodeisnotNone:print(node.data,end=" ")node=node.nextif__name__=="__main__":arr=[]node1=Node(1)node1.next=Node(3)node1.next.next=Node(5)node1.next.next.next=Node(7)arr.append(node1)node2=Node(2)node2.next=Node(4)node2.next.next=Node(6)node2.next.next.next=Node(8)arr.append(node2)node3=Node(0)node3.next=Node(9)node3.next.next=Node(10)node3.next.next.next=Node(11)arr.append(node3)head=mergeKLists(arr)printList(head)
C#
// C# program to merge K sorted linked listsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodemergeTwo(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;}staticNodemergeKLists(List<Node>arr){// Initialize result as emptyNoderes=null;// One by one merge all lists with // res and keep updating resforeach(Nodenodeinarr)res=mergeTwo(res,node);returnres;}staticvoidprintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}}staticvoidMain(string[]args){List<Node>arr=newList<Node>();Nodenode1=newNode(1);node1.next=newNode(3);node1.next.next=newNode(5);node1.next.next.next=newNode(7);arr.Add(node1);Nodenode2=newNode(2);node2.next=newNode(4);node2.next.next=newNode(6);node2.next.next.next=newNode(8);arr.Add(node2);Nodenode3=newNode(0);node3.next=newNode(9);node3.next.next=newNode(10);node3.next.next.next=newNode(11);arr.Add(node3);Nodehead=mergeKLists(arr);printList(head);}}
JavaScript
// JavaScript program to merge K sorted linked listsclassNode{constructor(x){this.data=x;this.next=null;}}// Function to merge only 2 listsfunctionmergeTwo(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;}// Function to merge K sorted linked listsfunctionmergeKLists(arr){// Initialize result as emptyletres=null;// One by one merge all lists with // res and keep updating resfor(letnodeofarr)res=mergeTwo(res,node);returnres;}functionprintList(node){while(node!==null){console.log(node.data+" ");node=node.next;}}letarr=[];letnode1=newNode(1);node1.next=newNode(3);node1.next.next=newNode(5);node1.next.next.next=newNode(7);arr.push(node1);letnode2=newNode(2);node2.next=newNode(4);node2.next.next=newNode(6);node2.next.next.next=newNode(8);arr.push(node2);letnode3=newNode(0);node3.next=newNode(9);node3.next.next=newNode(10);node3.next.next.next=newNode(11);arr.push(node3);lethead=mergeKLists(arr);printList(head);
Output
0 1 2 3 4 5 6 7 8 9 10 11
Time complexity: O(n*k*k), For simplicity, let us assume that every list is of equal size n. In the worst case. we take n + 2n + 3n ..... + k * n time. The sum of this series is n * k * (k + 1) / 2 which is O(n * k * k). Auxiliary Space: O(1).
[Naive Approach - 2] - Repeatedly Select Min of All Remaining
The idea is to iterate through all the k head nodes and append the head node with minimum value to the resultant list. Increment the head to next node. Repeat this process until all nodes are processed.
Step by step approach:
Initialize a dummy head for the resultant list.
Find the node with the smallest value in all the k lists.
Increment the current pointer to the next node of the list where the smallest node is found.
Append the node with smallest value to the resultant list.
Repeat these steps till all nodes have been used.
C++
// C++ program to merge K sorted linked lists#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to get node with minimum valueNode*getMinNode(vector<Node*>&arr){Node*mini=nullptr;intindex=-1;for(inti=0;i<arr.size();i++){// If current list is processedif(arr[i]==nullptr)continue;// If min node is not set or // current head has smaller value.if(mini==nullptr||arr[i]->data<mini->data){index=i;mini=arr[i];}}// Increment the head node if(index!=-1)arr[index]=arr[index]->next;returnmini;}// Function to merge K sorted linked listsNode*mergeKLists(vector<Node*>&arr){// Create a dummy node to simplify // the merging processNode*dummy=newNode(-1);Node*tail=dummy;Node*mini=getMinNode(arr);// Process all nodes.while(mini!=nullptr){// Append min node to the result.tail->next=mini;tail=mini;// Find the next min node mini=getMinNode(arr);}// Return the merged list starting// from the next of dummy nodereturndummy->next;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}}intmain(){intk=3;vector<Node*>arr(k);arr[0]=newNode(1);arr[0]->next=newNode(3);arr[0]->next->next=newNode(5);arr[0]->next->next->next=newNode(7);arr[1]=newNode(2);arr[1]->next=newNode(4);arr[1]->next->next=newNode(6);arr[1]->next->next->next=newNode(8);arr[2]=newNode(0);arr[2]->next=newNode(9);arr[2]->next->next=newNode(10);arr[2]->next->next->next=newNode(11);Node*head=mergeKLists(arr);printList(head);return0;}
Java
// Java program to merge K sorted linked listsimportjava.util.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to get node with minimum valuestaticNodegetMinNode(List<Node>arr){Nodemini=null;intindex=-1;for(inti=0;i<arr.size();i++){// If current list is processedif(arr.get(i)==null)continue;// If min node is not set or // current head has smaller value.if(mini==null||arr.get(i).data<mini.data){index=i;mini=arr.get(i);}}// Increment the head node if(index!=-1)arr.set(index,arr.get(index).next);returnmini;}// Function to merge K sorted linked listsstaticNodemergeKLists(List<Node>arr){Nodedummy=newNode(-1);Nodetail=dummy;Nodemini=getMinNode(arr);// Process all nodes.while(mini!=null){// Append min node to the result.tail.next=mini;tail=mini;// Find the next min node mini=getMinNode(arr);}returndummy.next;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}}publicstaticvoidmain(String[]args){List<Node>arr=newArrayList<>();arr.add(newNode(1));arr.get(0).next=newNode(3);arr.get(0).next.next=newNode(5);arr.get(0).next.next.next=newNode(7);arr.add(newNode(2));arr.get(1).next=newNode(4);arr.get(1).next.next=newNode(6);arr.get(1).next.next.next=newNode(8);arr.add(newNode(0));arr.get(2).next=newNode(9);arr.get(2).next.next=newNode(10);arr.get(2).next.next.next=newNode(11);Nodehead=mergeKLists(arr);printList(head);}}
Python
# Python program to merge K sorted linked listsclassNode:def__init__(self,x):self.data=xself.next=None# Function to get node with minimum valuedefgetMinNode(arr):mini=Noneindex=-1foriinrange(len(arr)):# If current list is processedifarr[i]isNone:continue# If min node is not set or # current head has smaller value.ifminiisNoneorarr[i].data<mini.data:index=imini=arr[i]# Increment the head nodeifindex!=-1:arr[index]=arr[index].nextreturnmini# Function to merge K sorted linked listsdefmergeKLists(arr):dummy=Node(-1)tail=dummymini=getMinNode(arr)# Process all nodes.whilemini:# Append min node to the result.tail.next=minitail=mini# Find the next min nodemini=getMinNode(arr)returndummy.nextdefprintList(node):whilenode:print(node.data,end=" ")node=node.nextif__name__=="__main__":arr=[None]*3arr[0]=Node(1)arr[0].next=Node(3)arr[0].next.next=Node(5)arr[0].next.next.next=Node(7)arr[1]=Node(2)arr[1].next=Node(4)arr[1].next.next=Node(6)arr[1].next.next.next=Node(8)arr[2]=Node(0)arr[2].next=Node(9)arr[2].next.next=Node(10)arr[2].next.next.next=Node(11)head=mergeKLists(arr)printList(head)
C#
// C# program to merge K sorted linked listsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to get node with minimum valuestaticNodegetMinNode(List<Node>arr){Nodemini=null;intindex=-1;for(inti=0;i<arr.Count;i++){// If current list is processedif(arr[i]==null)continue;// If min node is not set or // current head has smaller value.if(mini==null||arr[i].data<mini.data){index=i;mini=arr[i];}}// Increment the head nodeif(index!=-1)arr[index]=arr[index].next;returnmini;}// Function to merge K sorted linked listsstaticNodemergeKLists(List<Node>arr){Nodedummy=newNode(-1);Nodetail=dummy;Nodemini=getMinNode(arr);// Process all nodes.while(mini!=null){// Append min node to the result.tail.next=mini;tail=mini;// Find the next min nodemini=getMinNode(arr);}returndummy.next;}staticvoidprintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}}staticvoidMain(){List<Node>arr=newList<Node>();arr.Add(newNode(1));arr[0].next=newNode(3);arr[0].next.next=newNode(5);arr[0].next.next.next=newNode(7);arr.Add(newNode(2));arr[1].next=newNode(4);arr[1].next.next=newNode(6);arr[1].next.next.next=newNode(8);arr.Add(newNode(0));arr[2].next=newNode(9);arr[2].next.next=newNode(10);arr[2].next.next.next=newNode(11);Nodehead=mergeKLists(arr);printList(head);}}
JavaScript
// JavaScript program to merge K sorted linked listsclassNode{constructor(x){this.data=x;this.next=null;}}// Function to get node with minimum valuefunctiongetMinNode(arr){letmini=null;letindex=-1;for(leti=0;i<arr.length;i++){// If current list is processedif(arr[i]===null)continue;// If min node is not set or // current head has smaller value.if(mini===null||arr[i].data<mini.data){index=i;mini=arr[i];}}// Increment the head nodeif(index!==-1)arr[index]=arr[index].next;returnmini;}// Function to merge K sorted linked listsfunctionmergeKLists(arr){letdummy=newNode(-1);lettail=dummy;letmini=getMinNode(arr);// Process all nodes.while(mini!==null){// Append min node to the result.tail.next=mini;tail=mini;// Find the next min nodemini=getMinNode(arr);}returndummy.next;}functionprintList(node){while(node!==null){console.log(node.data+" ");node=node.next;}}letarr=[];arr.push(newNode(1));arr[0].next=newNode(3);arr[0].next.next=newNode(5);arr[0].next.next.next=newNode(7);arr.push(newNode(2));arr[1].next=newNode(4);arr[1].next.next=newNode(6);arr[1].next.next.next=newNode(8);arr.push(newNode(0));arr[2].next=newNode(9);arr[2].next.next=newNode(10);arr[2].next.next.next=newNode(11);lethead=mergeKLists(arr);printList(head);
Output
0 1 2 3 4 5 6 7 8 9 10 11
Time complexity: O(n * k2), There are n*k nodes in total (assuming every list has O(n) nodes) and to find the smallest node it takes k times so for the n*k nodes it will take n*k*k time. Auxiliary Space: O(1)
[Expected Approach - 1] - Using Min Heap (Works better for unequal sized lists)
This solution is mainly an optimization over the previous approach. Instead of linearly traversing the array to find the minimum, we use min heap data structure and reduce the time complexity of this operation to O(Log k).
Time Complexity: O(n * k * log k) if we have k lists of size O(n) each. We can also say O(n * Log k) where n is the total number of nodes. Auxiliary Space: O(k)
[Expected Approach - 2] - UsingDivide and Conquer (Works better for equal sized lists)
The idea is to use divide and conquer by recursively splitting the k lists into two halves until we have pairs of lists to merge, then merge these pairs using a two-way merge procedure (similar to merge sort's merge step), and continue this process back up through the recursion tree until all lists are merged into a single sorted list.
Step by step approach:
Split k lists into two parts: lists[0...mid] and lists[mid+1...end].
Recursively merge the left half of lists to get first sorted list.
Recursively merge the right half of lists to get second sorted list.
Merge the above two sorted lists using two-pointer approach.
Return the final merged sorted list.
C++
// C++ program to merge K sorted linked lists#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to merge two sorted lists.Node*mergeTwo(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;}Node*mergeListsRecur(inti,intj,vector<Node*>&arr){// If single list is leftif(i==j)returnarr[i];// Find the middle of listsintmid=i+(j-i)/2;// Merge lists from i to mid Node*head1=mergeListsRecur(i,mid,arr);// Merge lists from mid+1 to j Node*head2=mergeListsRecur(mid+1,j,arr);// Merge the above 2 lists Node*head=mergeTwo(head1,head2);returnhead;}// Function to merge K sorted linked listsNode*mergeKLists(vector<Node*>&arr){// Base case for 0 lists if(arr.size()==0)returnnullptr;returnmergeListsRecur(0,arr.size()-1,arr);}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}}intmain(){intk=3;vector<Node*>arr(k);arr[0]=newNode(1);arr[0]->next=newNode(3);arr[0]->next->next=newNode(5);arr[0]->next->next->next=newNode(7);arr[1]=newNode(2);arr[1]->next=newNode(4);arr[1]->next->next=newNode(6);arr[1]->next->next->next=newNode(8);arr[2]=newNode(0);arr[2]->next=newNode(9);arr[2]->next->next=newNode(10);arr[2]->next->next->next=newNode(11);Node*head=mergeKLists(arr);printList(head);return0;}
Java
// Java program to merge K sorted linked listsimportjava.util.List;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to merge two sorted lists.staticNodemergeTwo(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;}staticNodemergeListsRecur(inti,intj,List<Node>arr){// If single list is leftif(i==j)returnarr.get(i);// Find the middle of listsintmid=i+(j-i)/2;// Merge lists from i to mid Nodehead1=mergeListsRecur(i,mid,arr);// Merge lists from mid+1 to j Nodehead2=mergeListsRecur(mid+1,j,arr);// Merge the above 2 lists Nodehead=mergeTwo(head1,head2);returnhead;}// Function to merge K sorted linked listsstaticNodemergeKLists(List<Node>arr){// Base case for 0 lists if(arr.size()==0)returnnull;returnmergeListsRecur(0,arr.size()-1,arr);}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}}publicstaticvoidmain(String[]args){intk=3;List<Node>arr=newjava.util.ArrayList<>();arr.add(newNode(1));arr.get(0).next=newNode(3);arr.get(0).next.next=newNode(5);arr.get(0).next.next.next=newNode(7);arr.add(newNode(2));arr.get(1).next=newNode(4);arr.get(1).next.next=newNode(6);arr.get(1).next.next.next=newNode(8);arr.add(newNode(0));arr.get(2).next=newNode(9);arr.get(2).next.next=newNode(10);arr.get(2).next.next.next=newNode(11);Nodehead=mergeKLists(arr);printList(head);}}
Python
# Python program to merge K sorted linked listsclassNode:def__init__(self,x):self.data=xself.next=None# Function to merge two sorted lists.defmergeTwo(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.nextdefmergeListsRecur(i,j,arr):# If single list is leftifi==j:returnarr[i]# Find the middle of listsmid=i+(j-i)//2# Merge lists from i to mid head1=mergeListsRecur(i,mid,arr)# Merge lists from mid+1 to j head2=mergeListsRecur(mid+1,j,arr)# Merge the above 2 lists head=mergeTwo(head1,head2)returnhead# Function to merge K sorted linked listsdefmergeKLists(arr):# Base case for 0 lists iflen(arr)==0:returnNonereturnmergeListsRecur(0,len(arr)-1,arr)defprintList(node):whilenodeisnotNone:print(node.data,end=" ")node=node.nextif__name__=="__main__":k=3arr=[None]*karr[0]=Node(1)arr[0].next=Node(3)arr[0].next.next=Node(5)arr[0].next.next.next=Node(7)arr[1]=Node(2)arr[1].next=Node(4)arr[1].next.next=Node(6)arr[1].next.next.next=Node(8)arr[2]=Node(0)arr[2].next=Node(9)arr[2].next.next=Node(10)arr[2].next.next.next=Node(11)head=mergeKLists(arr)printList(head)
C#
// C# program to merge K sorted linked listsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to merge two sorted lists.staticNodemergeTwo(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;}staticNodemergeListsRecur(inti,intj,List<Node>arr){// If single list is leftif(i==j)returnarr[i];// Find the middle of listsintmid=i+(j-i)/2;// Merge lists from i to mid Nodehead1=mergeListsRecur(i,mid,arr);// Merge lists from mid+1 to j Nodehead2=mergeListsRecur(mid+1,j,arr);// Merge the above 2 lists Nodehead=mergeTwo(head1,head2);returnhead;}// Function to merge K sorted linked listsstaticNodemergeKLists(List<Node>arr){// Base case for 0 lists if(arr.Count==0)returnnull;returnmergeListsRecur(0,arr.Count-1,arr);}staticvoidprintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}}staticvoidMain(string[]args){List<Node>arr=newList<Node>();arr.Add(newNode(1));arr[0].next=newNode(3);arr[0].next.next=newNode(5);arr[0].next.next.next=newNode(7);arr.Add(newNode(2));arr[1].next=newNode(4);arr[1].next.next=newNode(6);arr[1].next.next.next=newNode(8);arr.Add(newNode(0));arr[2].next=newNode(9);arr[2].next.next=newNode(10);arr[2].next.next.next=newNode(11);Nodehead=mergeKLists(arr);printList(head);}}
JavaScript
// JavaScript program to merge K sorted linked listsclassNode{constructor(x){this.data=x;this.next=null;}}// Function to merge two sorted lists.functionmergeTwo(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;}functionmergeListsRecur(i,j,arr){// If single list is leftif(i===j)returnarr[i];// Find the middle of listsletmid=i+Math.floor((j-i)/2);// Merge lists from i to mid lethead1=mergeListsRecur(i,mid,arr);// Merge lists from mid+1 to j lethead2=mergeListsRecur(mid+1,j,arr);// Merge the above 2 lists returnmergeTwo(head1,head2);}// Function to merge K sorted linked listsfunctionmergeKLists(arr){// Base case for 0 lists if(arr.length===0)returnnull;returnmergeListsRecur(0,arr.length-1,arr);}functionprintList(node){while(node!==null){console.log(node.data+" ");node=node.next;}}letk=3;letarr=[];arr[0]=newNode(1);arr[0].next=newNode(3);arr[0].next.next=newNode(5);arr[0].next.next.next=newNode(7);arr[1]=newNode(2);arr[1].next=newNode(4);arr[1].next.next=newNode(6);arr[1].next.next.next=newNode(8);arr[2]=newNode(0);arr[2].next=newNode(9);arr[2].next.next=newNode(10);arr[2].next.next.next=newNode(11);lethead=mergeKLists(arr);printList(head);
Output
0 1 2 3 4 5 6 7 8 9 10 11
Time Complexity: O(n * k * log k), where n is the number of nodes in the longest list. Auxiliary Space: O(log k), used for recursion.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.