In a linked list, every node has two pointers: next and bottom. The heads of n linked lists are connected using the next pointer, while the bottom pointer points to the next node in the current linked list.
Each linked list is sorted in non-decreasing order of data, and the head nodes are also sorted in non-decreasing order.
Given the head of the first linked list, flatten the linked lists into a single sorted linked list such that every node is connected using only the bottom pointers.
Examples:Â
Input:
Output: 5 -> 7 -> 8 -> 10 -> 19 -> 20 -> 22 -> 28 -> 40 -> 45. Explanation: Bottom pointer of 5 is pointing to 7. Bottom pointer of 7 is pointing to 8. Bottom pointer of 10 is pointing to 20 and so on. So, after flattening the linked list the sorted list will be 5 -> 7 -> 8 -> 10 -> 19 -> 20 -> 22 -> 28 -> 40 -> 45.
Input:
Output: 5 -> 7 -> 8 -> 10 -> 19 -> 22 -> 28 -> 30 -> 50 Explanation: Bottom pointer of 5 is pointing to 7. Bottom pointer of 7 is pointing to 8. Bottom pointer of 8 is pointing to 30 and so on. So, after flattening the linked list the sorted list will be 5 -> 7 -> 8 -> 10 -> 19 -> 22 -> 28 -> 30 -> 50.
[Naive Approach] Recursion and Merging - O(n * n * m) Time and O(n) Space
The idea is similar to Merge two sorted linked lists. We recursively flatten the list connected through the next pointer and merge each sublist with the already flattened list in sorted order using the bottom pointer.
Working of Approach:
Using recursion, first go to the last head node.
Merge each linked list (connected via bottom pointers) with the already flattened list in sorted order.
Move one step back and merge the previous list with the merged result.
Continue this process until the first list is merged.
Return the final flattened and sorted list connected through bottom pointers.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next,*bottom;Node(intnewdata){data=newdata;next=bottom=nullptr;}};// Utility function to merge two sorted linked lists// using their bottom pointersNode*merge(Node*head1,Node*head2){// A dummy first node to store the result listNodedummy(-1);// Tail points to the last result node to add new nodes// to the resultNode*tail=&dummy;// Iterate till either head1 or head2 does not reach NULLwhile(head1&&head2){if(head1->data<=head2->data){// append head1 to the resulttail->bottom=head1;head1=head1->bottom;}else{// append head2 to the resulttail->bottom=head2;head2=head2->bottom;}// Move tail pointer to the next nodetail=tail->bottom;}// Append the remaining nodes of non-null linked listif(!head1)tail->bottom=head2;elsetail->bottom=head1;return(dummy.bottom);}// function to flatten the linked listNode*flatten(Node*root){// Base Casesif(root==nullptr||root->next==nullptr)returnroot;// Recur for next listroot->next=flatten(root->next);// Now merge the current and next listroot=merge(root,root->next);// Return the rootreturnroot;}voidprintList(Node*head){Node*temp=head;while(temp!=nullptr){cout<<temp->data;if(temp->bottom)cout<<" -> ";temp=temp->bottom;}cout<<endl;}intmain(){/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30 */Node*head=newNode(5);head->bottom=newNode(7);head->bottom->bottom=newNode(8);head->bottom->bottom->bottom=newNode(30);head->next=newNode(10);head->next->bottom=newNode(20);head->next->next=newNode(19);head->next->next->bottom=newNode(22);head->next->next->bottom->bottom=newNode(50);head->next->next->next=newNode(28);head=flatten(head);printList(head);return0;}
C
#include<stdio.h>structNode{intdata;structNode*next,*bottom;};// Utility function to merge two sorted linked lists using// their bottom pointersstructNode*merge(structNode*head1,structNode*head2){// A dummy first node to store the result liststructNodedummy;dummy.data=-1;dummy.bottom=NULL;// Tail points to the last result node to add new nodes// to the resultstructNode*tail=&dummy;// Iterate till either head1 or head2 does not reach// NULLwhile(head1&&head2){if(head1->data<=head2->data){// append head1 to the resulttail->bottom=head1;head1=head1->bottom;}else{// append head2 to the resulttail->bottom=head2;head2=head2->bottom;}// Move tail pointer to the next nodetail=tail->bottom;}// Append the remaining nodes of non-null linked listif(!head1)tail->bottom=head2;elsetail->bottom=head1;returndummy.bottom;}// Function to flatten the linked liststructNode*flatten(structNode*root){// Base Casesif(root==NULL||root->next==NULL)returnroot;// Recur for next listroot->next=flatten(root->next);// Now merge the current and next listroot=merge(root,root->next);// Return the rootreturnroot;}voidprintList(structNode*head){structNode*temp=head;while(temp!=NULL){printf("%d",temp->data);if(temp->bottom)printf(" -> ");temp=temp->bottom;}printf("\n");}// Function to create a new nodestructNode*createNode(intnewdata){structNode*newnode=(structNode*)malloc(sizeof(structNode));newnode->data=newdata;newnode->next=NULL;newnode->bottom=NULL;returnnewnode;}intmain(){/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30 */structNode*head=createNode(5);head->bottom=createNode(7);head->bottom->bottom=createNode(8);head->bottom->bottom->bottom=createNode(30);head->next=createNode(10);head->next->bottom=createNode(20);head->next->next=createNode(19);head->next->next->bottom=createNode(22);head->next->next->bottom->bottom=createNode(50);head->next->next->next=createNode(28);head=flatten(head);printList(head);return0;}
Java
classNode{intdata;Nodenext,bottom;Node(intnewData){data=newData;next=bottom=null;}}classGFG{// Utility function to merge two sorted linked lists// using their bottom pointersstaticNodemerge(Nodehead1,Nodehead2){// A dummy first node to store the result listNodedummy=newNode(-1);// Tail points to the last result node to add new// nodes to the resultNodetail=dummy;// Iterate till either head1 or head2 does not reach// nullwhile(head1!=null&&head2!=null){if(head1.data<=head2.data){// Append head1 to the resulttail.bottom=head1;head1=head1.bottom;}else{// Append head2 to the resulttail.bottom=head2;head2=head2.bottom;}// Move tail pointer to the next nodetail=tail.bottom;}// Append the remaining nodes of the non-null listif(head1!=null)tail.bottom=head1;elsetail.bottom=head2;returndummy.bottom;}// Function to flatten the linked liststaticNodeflatten(Noderoot){// Base Casesif(root==null||root.next==null)returnroot;// Recur for next listroot.next=flatten(root.next);// Now merge the current and next listroot=merge(root,root.next);// Return the rootreturnroot;}staticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){System.out.print(temp.data);if(temp.bottom!=null){System.out.print(" -> ");}temp=temp.bottom;}System.out.println();}publicstaticvoidmain(String[]args){/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30 */Nodehead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);printList(head);}}
Python
classNode:def__init__(self,new_data):self.data=new_dataself.next=Noneself.bottom=None# Utility function to merge two sorted linked lists # using their bottom pointersdefmerge(head1,head2):# A dummy first node to store the result listdummy=Node(-1)tail=dummy# Iterate till either head1 or head2 does not reach Nonewhilehead1andhead2:ifhead1.data<=head2.data:# Append head1 to the resulttail.bottom=head1head1=head1.bottomelse:# Append head2 to the resulttail.bottom=head2head2=head2.bottom# Move tail pointer to the next nodetail=tail.bottom# Append the remaining nodes of the non-null linked listifhead1:tail.bottom=head1else:tail.bottom=head2returndummy.bottom# Function to flatten the linked listdefflatten(root):# Base CasesifrootisNoneorroot.nextisNone:returnroot# Recur for next listroot.next=flatten(root.next)# Now merge the current and next listroot=merge(root,root.next)# Return the rootreturnrootdefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.bottomisnotNone:print(" -> ",end="")node=node.bottomprint()if__name__=="__main__":# Create a hard-coded linked list:# 5 -> 10 -> 19 -> 28# | | | # V V V # 7 20 22 # | | # V V # 8 50 # | # V # 30 head=Node(5)head.bottom=Node(7)head.bottom.bottom=Node(8)head.bottom.bottom.bottom=Node(30)head.next=Node(10)head.next.bottom=Node(20)head.next.next=Node(19)head.next.next.bottom=Node(22)head.next.next.bottom.bottom=Node(50)head.next.next.next=Node(28)head=flatten(head)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNodebottom;publicNode(intnewData){data=newData;next=null;bottom=null;}}classGFG{// Utility function to merge two sorted linked lists// using their bottom pointersstaticNodeMerge(Nodehead1,Nodehead2){// A dummy first node to store the result listNodedummy=newNode(-1);// Tail points to the last result nodeNodetail=dummy;// Iterate until either list becomes nullwhile(head1!=null&&head2!=null){if(head1.data<=head2.data){tail.bottom=head1;head1=head1.bottom;}else{tail.bottom=head2;head2=head2.bottom;}tail=tail.bottom;}// Append the remaining nodesif(head1==null)tail.bottom=head2;elsetail.bottom=head1;returndummy.bottom;}// Function to flatten the linked liststaticNodeflatten(Noderoot){// Base casesif(root==null||root.next==null)returnroot;// Recursively flatten the next listroot.next=flatten(root.next);// Merge the current and next listsroot=Merge(root,root.next);returnroot;}// Function to print the flattened linked liststaticvoidPrintList(Nodehead){Nodetemp=head;while(temp!=null){Console.Write(temp.data);if(temp.bottom!=null)Console.Write(" -> ");temp=temp.bottom;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 5 -> 10 -> 19 -> 28// | | |// 7 20 22// | |// 8 50// |// 30Nodehead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);PrintList(head);}}
JavaScript
// Javascript program for flattening a Linked ListclassNode{constructor(newData){this.data=newData;this.next=null;this.bottom=null;}}// Utility function to merge two sorted linked lists// using their bottom pointersfunctionmerge(head1,head2){// A dummy first node to store the result listletdummy=newNode(-1);// Tail points to the last result node to add new nodes// to the resultlettail=dummy;// Iterate till either head1 or head2 does not reach// nullwhile(head1!==null&&head2!==null){if(head1.data<=head2.data){// Append head1 to the resulttail.bottom=head1;head1=head1.bottom;}else{// Append head2 to the resulttail.bottom=head2;head2=head2.bottom;}// Move tail pointer to the next nodetail=tail.bottom;}// Append the remaining nodes of non-null linked listif(head1===null)tail.bottom=head2;elsetail.bottom=head1;returndummy.bottom;}// Function to flatten the linked listfunctionflatten(root){// Base Casesif(root===null||root.next===null){returnroot;}// Recur for next listroot.next=flatten(root.next);// Now merge the current and next listroot=merge(root,root.next);// Return the rootreturnroot;}functionprintList(node){while(node!==null){process.stdout.write(node.data.toString());if(node.bottom!==null){process.stdout.write(" -> ");}node=node.bottom;}}// Driver Code/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30*/lethead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);printList(head);
Time Complexity: O(n * n * m) - where n is the no of nodes in the main linked list and m is the no of nodes in a single sub-linked list.Â
After adding the first 2 lists, the time taken will be O(m+m) = O(2m).
Then we will merge another list to above merged list -> time = O(2m + m) = O(3m).
We will keep merging lists to previously merged lists until all lists are merged.
Total time taken will be O(2m + 3m + 4m + .... n*m) = (2 + 3 + 4 + ... + n) * m = O(n * n * m)
[Better Approach] Sorting - O(n * m * log(n * m)) Time and O(n * m) Space
The idea is to traverse the linked list and push the values of all nodes into an array. Then, sort the array in ascending order and create a new linked list by traversing the sorted array.
Working of Approach:
Traverse the entire linked list using:
Outer loop -> move along the next pointer.
Inner loop -> move along the bottom pointer.
Push every node's data into the array.
After traversal, sort the array in ascending order.
Create a new linked list using the sorted array, connecting consecutive nodes through the bottom pointer.
Return the head of the newly created linked list — this is the flattened, sorted list.
C++
#include<algorithm>#include<iostream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*next,*bottom;Node(intnewdata){data=newdata;next=bottom=nullptr;}};// function to flatten the linked listNode*flatten(Node*root){vector<int>values;// Push values of all nodes into an arraywhile(root!=nullptr){// Push the head node of the sub-linked-listvalues.push_back(root->data);// Push all the nodes of the sub-linked-listNode*temp=root->bottom;while(temp!=nullptr){values.push_back(temp->data);temp=temp->bottom;}// Move to the next head noderoot=root->next;}// Sort the node values in ascending ordersort(values.begin(),values.end());// Construct the new flattened linked listNode*tail=nullptr;Node*head=nullptr;for(inti=0;i<values.size();i++){Node*newNode=newNode(values[i]);// If this is the first node of the linked list,// make the node as headif(head==nullptr){head=newNode;}else{tail->bottom=newNode;}tail=newNode;}returnhead;}voidprintList(Node*head){Node*temp=head;while(temp!=nullptr){cout<<temp->data;if(temp->bottom)cout<<" -> ";temp=temp->bottom;}cout<<endl;}intmain(){// Create a hard-coded linked list:// 5 -> 10 -> 19 -> 28// | | |// V V V// 7 20 22// | |// V V// 8 50// |// V// 30Node*head=newNode(5);head->bottom=newNode(7);head->bottom->bottom=newNode(8);head->bottom->bottom->bottom=newNode(30);head->next=newNode(10);head->next->bottom=newNode(20);head->next->next=newNode(19);head->next->next->bottom=newNode(22);head->next->next->bottom->bottom=newNode(50);head->next->next->next=newNode(28);head=flatten(head);printList(head);return0;}
Java
importjava.util.*;classNode{intdata;Nodenext,bottom;Node(intnewData){data=newData;next=bottom=null;}}classGFG{// Function to flatten the linked liststaticNodeflatten(Noderoot){List<Integer>values=newArrayList<>();// Push values of all nodes into a listwhile(root!=null){// Push the head node of the sub-linked-listvalues.add(root.data);// Push all the nodes of the sub-linked-listNodetemp=root.bottom;while(temp!=null){values.add(temp.data);temp=temp.bottom;}// Move to the next head noderoot=root.next;}// Sort the node values in ascending orderCollections.sort(values);// Construct the new flattened linked listNodetail=null;Nodehead=null;for(intvalue:values){NodenewNode=newNode(value);// If this is the first node of the linked list,// make the node as headif(head==null)head=newNode;elsetail.bottom=newNode;tail=newNode;}returnhead;}// Function to print the linked liststaticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){System.out.print(temp.data);if(temp.bottom!=null)System.out.print(" -> ");temp=temp.bottom;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 5 -> 10 -> 19 -> 28// | | |// V V V// 7 20 22// | |// V V// 8 50// |// V// 30Nodehead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);printList(head);}}
Python
classNode:def__init__(self,new_data):self.data=new_dataself.next=Noneself.bottom=None# Function to flatten the linked listdefflatten(root):values=[]# Push values of all nodes into an arraywhilerootisnotNone:# Push the head node of the sub-linked-listvalues.append(root.data)# Push all the nodes of the sub-linked-listtemp=root.bottomwhiletempisnotNone:values.append(temp.data)temp=temp.bottom# Move to the next head noderoot=root.next# Sort the node values in ascending ordervalues.sort()# Construct the new flattened linked listtail=Nonehead=Noneforvalueinvalues:newNode=Node(value)# If this is the first node of the linked list,# make the node as headifheadisNone:head=newNodeelse:tail.bottom=newNodetail=newNodereturnheaddefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.nextisnotNone:print(" -> ",end="")node=node.nextprint()if__name__=="__main__":# Create a hard-coded linked list:# 5 -> 10 -> 19 -> 28# | | |# V V V# 7 20 22# | |# V V# 8 50# |# V# 30head=Node(5)head.bottom=Node(7)head.bottom.bottom=Node(8)head.bottom.bottom.bottom=Node(30)head.next=Node(10)head.next.bottom=Node(20)head.next.next=Node(19)head.next.next.bottom=Node(22)head.next.next.bottom.bottom=Node(50)head.next.next.next=Node(28)head=flatten(head)printList(head)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext,bottom;publicNode(intnewData){data=newData;next=bottom=null;}}classGFG{// Function to flatten the linked liststaticNodeflatten(Noderoot){List<int>values=newList<int>();// Push values of all nodes into a listwhile(root!=null){values.Add(root.data);// Push all nodes of the sub-linked-listNodetemp=root.bottom;while(temp!=null){values.Add(temp.data);temp=temp.bottom;}// Move to the next head noderoot=root.next;}// Sort node values in ascending ordervalues.Sort();// Construct the new flattened linked listNodehead=null;Nodetail=null;foreach(intvalueinvalues){NodenewNode=newNode(value);if(head==null){head=newNode;}else{tail.bottom=newNode;}tail=newNode;}returnhead;}// Function to print the flattened linked liststaticvoidPrintList(Nodehead){Nodetemp=head;while(temp!=null){Console.Write(temp.data);if(temp.bottom!=null)Console.Write(" -> ");temp=temp.bottom;}Console.WriteLine();}staticvoidMain(){// Create the linked list// 5 -> 10 -> 19 -> 28// | | |// 7 20 22// | |// 8 50// |// 30Nodehead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);PrintList(head);}}
JavaScript
classNode{constructor(newData){this.data=newData;this.next=null;this.bottom=null;}}// Function to flatten the linked listfunctionflatten(root){letvalues=[];// Push values of all nodes into an arraywhile(root!==null){// Push the head node of the sub-linked-listvalues.push(root.data);// Push all the nodes of the sub-linked-listlettemp=root.bottom;while(temp!==null){values.push(temp.data);temp=temp.bottom;}// Move to the next head noderoot=root.next;}// Sort the node values in ascending ordervalues.sort((a,b)=>a-b);// Construct the new flattened linked listlethead=null;lettail=null;for(letvalueofvalues){letnewNode=newNode(value);// If this is the first node of the linked list,// make the node as headif(head===null)head=newNode;elsetail.bottom=newNode;tail=newNode;}returnhead;}// Function to print the linked listfunctionprintList(node){while(node!==null){process.stdout.write(node.data.toString());if(node.bottom!==null){process.stdout.write(" -> ");}node=node.bottom;}}/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30*/lethead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);printList(head);
[Expected Approach] Min-Heap - O(n * m * log(n)) Time and O(n) Space
The idea is to use a min-heap to store the head node of each sublist and repeatedly extract the smallest node to build the flattened sorted list.
Working of Approach:
Create a min-heap using a lambda comparator and push the head node of each sublist into it.
Use a dummy node to build the result list.
While the heap is not empty, extract the smallest node, append it to the result, set its next pointer to nullptr, and push its bottom node into the heap if it exists.
Set the last node's bottom pointer to nullptr and return dummy.bottom.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next,*bottom;Node(intnewdata){data=newdata;next=bottom=nullptr;}};// Comparator for the min-heapstructCompare{booloperator()(Node*a,Node*b){returna->data>b->data;}};// Function to flatten the linked listNode*flatten(Node*head){if(head==nullptr)returnnullptr;// Min-heap to store the current node of each sublistpriority_queue<Node*,vector<Node*>,Compare>pq;// Push the head of every sublist into the heapwhile(head!=nullptr){pq.push(head);head=head->next;}// Dummy node to construct the flattened listNodedummy(-1);Node*tail=&dummy;// Process nodes in ascending orderwhile(!pq.empty()){// Get the node with the smallest valueNode*curr=pq.top();pq.pop();// Push the next node of the same sublistif(curr->bottom!=nullptr)pq.push(curr->bottom);// Append the current node to the resulttail->bottom=curr;tail=curr;// Remove the next pointertail->next=nullptr;}// Mark the end of the flattened listtail->bottom=nullptr;returndummy.bottom;}intmain(){/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30 */Node*head=newNode(5);head->bottom=newNode(7);head->bottom->bottom=newNode(8);head->bottom->bottom->bottom=newNode(30);head->next=newNode(10);head->next->bottom=newNode(20);head->next->next=newNode(19);head->next->next->bottom=newNode(22);head->next->next->bottom->bottom=newNode(50);head->next->next->next=newNode(28);head=flatten(head);// Print the flattened linked listautoprintList=[](Node*head){Node*temp=head;while(temp!=nullptr){cout<<temp->data;if(temp->bottom!=nullptr)cout<<" -> ";temp=temp->bottom;}cout<<endl;};printList(head);return0;}
Java
importjava.util.*;classNode{intdata;Nodenext,bottom;Node(intnewdata){data=newdata;next=bottom=null;}}publicclassGFG{// Comparator for the min-heapstaticclassCompareimplementsComparator<Node>{publicintcompare(Nodea,Nodeb){returnInteger.compare(a.data,b.data);}}// Function to flatten the linked liststaticNodeflatten(Nodehead){if(head==null)returnnull;// Min-heap to store the current node of each// sublistPriorityQueue<Node>pq=newPriorityQueue<>(newCompare());// Push the head of every sublist into the heapwhile(head!=null){pq.offer(head);head=head.next;}// Dummy node to construct the flattened listNodedummy=newNode(-1);Nodetail=dummy;// Process nodes in ascending orderwhile(!pq.isEmpty()){// Get the node with the smallest valueNodecurr=pq.poll();// Push the next node of the same sublistif(curr.bottom!=null)pq.offer(curr.bottom);// Append the current node to the resulttail.bottom=curr;tail=curr;// Remove the next pointertail.next=null;}// Mark the end of the flattened listtail.bottom=null;returndummy.bottom;}publicstaticvoidmain(String[]args){/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30 */Nodehead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);// Print the flattened linked listNodetemp=head;while(temp!=null){System.out.print(temp.data);if(temp.bottom!=null)System.out.print(" -> ");temp=temp.bottom;}System.out.println();}}
Python
importheapqclassNode:def__init__(self,data):self.data=dataself.next=Noneself.bottom=Nonedefflatten(head):ifheadisNone:returnNone# Min-heap to store the current node of each listpq=[]idx=0# Push the head of every list into the heapwhileheadisnotNone:heapq.heappush(pq,(head.data,idx,head))idx+=1head=head.nextdummy=Node(-1)tail=dummywhilepq:# Get the smallest node_,_,curr=heapq.heappop(pq)# Push the next node of the same listifcurr.bottomisnotNone:heapq.heappush(pq,(curr.bottom.data,idx,curr.bottom))idx+=1# Append the current node to the resulttail.bottom=currtail=currtail.next=Nonetail.bottom=Nonereturndummy.bottomif__name__=="__main__":# Create the linked listhead=Node(5)head.bottom=Node(7)head.bottom.bottom=Node(8)head.bottom.bottom.bottom=Node(30)head.next=Node(10)head.next.bottom=Node(20)head.next.next=Node(19)head.next.next.bottom=Node(22)head.next.next.bottom.bottom=Node(50)head.next.next.next=Node(28)head=flatten(head)# Print the flattened linked listtemp=headwhiletempisnotNone:print(temp.data,end="")iftemp.bottomisnotNone:print(" -> ",end="")temp=temp.bottomprint()
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodenext,bottom;publicNode(intx){data=x;next=bottom=null;}}classGFG{publicNodeflatten(Nodehead){if(head==null)returnnull;// Min-heap to store the current node of each listvarpq=newPriorityQueue<Node,int>();// Push the head of every list into the heapwhile(head!=null){pq.Enqueue(head,head.data);head=head.next;}Nodedummy=newNode(-1);Nodetail=dummy;while(pq.Count>0){// Get the smallest nodeNodecurr=pq.Dequeue();// Push the next node of the same listif(curr.bottom!=null)pq.Enqueue(curr.bottom,curr.bottom.data);// Append the current node to the resulttail.bottom=curr;tail=curr;tail.next=null;}tail.bottom=null;returndummy.bottom;}}classProgram{staticvoidMain(){/* Create a hard-coded linked list: 5 -> 10 -> 19 -> 28 | | | V V V 7 20 22 | | V V 8 50 | V 30 */Nodehead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);GFGsol=newGFG();head=sol.flatten(head);// Print the flattened linked listNodetemp=head;while(temp!=null){Console.Write(temp.data);if(temp.bottom!=null)Console.Write(" -> ");temp=temp.bottom;}Console.WriteLine();}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;this.bottom=null;}}// Function to flatten the linked listfunctionflatten(head){if(head===null)returnnull;// Min-heap to store the current node of each listconstpq=[];// Insert a node into the min-heapfunctionpush(node){pq.push(node);leti=pq.length-1;while(i>0){letparent=Math.floor((i-1)/2);if(pq[parent].data<=pq[i].data)break;[pq[parent],pq[i]]=[pq[i],pq[parent]];i=parent;}}// Remove and return the smallest nodefunctionpop(){constresult=pq[0];constlast=pq.pop();if(pq.length>0){pq[0]=last;leti=0;while(true){letsmallest=i;letleft=2*i+1;letright=2*i+2;if(left<pq.length&&pq[left].data<pq[smallest].data)smallest=left;if(right<pq.length&&pq[right].data<pq[smallest].data)smallest=right;if(smallest===i)break;[pq[i],pq[smallest]]=[pq[smallest],pq[i]];i=smallest;}}returnresult;}// Push the head of every list into the heapwhile(head!==null){push(head);head=head.next;}constdummy=newNode(-1);lettail=dummy;while(pq.length>0){// Get the smallest nodeconstcurr=pop();// Push the next node of the same listif(curr.bottom!==null)push(curr.bottom);// Append the current node to the resulttail.bottom=curr;tail=curr;tail.next=null;}tail.bottom=null;returndummy.bottom;}// Driver Code// Create the linked listlethead=newNode(5);head.bottom=newNode(7);head.bottom.bottom=newNode(8);head.bottom.bottom.bottom=newNode(30);head.next=newNode(10);head.next.bottom=newNode(20);head.next.next=newNode(19);head.next.next.bottom=newNode(22);head.next.next.bottom.bottom=newNode(50);head.next.next.next=newNode(28);head=flatten(head);// Print the flattened linked listlettemp=head;letresult=[];while(temp!==null){result.push(temp.data);temp=temp.bottom;}console.log(result.join(" -> "));