Given a linked list containing n head nodes where every node in the linked list contains two pointers:
next points to the next node in the list.
bottom pointer to a sub-linked list where the current node is the head. Each of the sub-linked lists nodes and the head
nodes are sorted in ascending order based on their data .We need to flatten the linked list so that all the nodes appear in a single level while maintaining the sorted order.
[Approach 1] Using Sorting - O(n * m * log(n * m)) Time and O(n*m) Space
The idea is to traverse the linked list and push values of all the nodes in an array. Now, we can sort the array in ascending order, and create a new linked list by traversing the sorted array.
Follow the steps to solve the problem:
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.
Now, create a new linked list using the sorted array:
Return the bottom of the dummy node — this is the head of the flattened, sorted list.
C++
// C++ program for flattening a Linked List#include<iostream>#include<algorithm>#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
// Java Program for flattening a linked listimportjava.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
# Python program for flattening a Linked ListclassNode: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;usingSystem.Linq;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){// 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 ordervalues.Sort();// Construct the new flattened linked listNodetail=null;Nodehead=null;foreach(intvalueinvalues){NodenewNode=newNode(value);// If this is the first node of the linked list,// make the node as headif(head==null){head=newNode;}else{tail.Bottom=newNode;}tail=newNode;}returnhead;}// Function to print the 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 | | | 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);}}
JavaScript
// Javascript Program for flattening a linked listclassNode{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);
Using recursion, we first go to the last head node .
Then, we keep merging each linked list (connected via bottom pointers) with the result of the already flattened list in sorted order.
Move one step back and keep merging the previous list with the merged result.
Continue this process until the first list is merged.
The final result is a single flattened and sorted list using bottom pointers.
C++
// C++ program for flattening a Linked List#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
// C program for flattening a Linked List#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 list if(!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
// Java program for flattening a Linked ListclassNode{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
# Python3 program for flattening a Linked ListclassNode: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#
// C# program for flattening a Linked ListusingSystem;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 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 linked listif(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;// 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){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 | | | 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);}}
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;}}/* 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)
Auxiliary Space: O(n), the recursive functions will use a recursive stack of a size equivalent to a total number of nodes in the main linked list.
[Approach 3] Using Priority Queues - O(n * m * log(n)) Time and O(n) Space
The idea is to use a Min Heap, push all the head nodes into it, and always extract the node with the minimum value from the top.
Follow the steps to solve the problem:
Create a min-heap with custom comparator.
Push all head nodes to heap.
Use a dummy node to build the result.
While heap is not empty:
Pop smallest node.
Add it to result.
If it has a bottom node, push that into heap.
Return dummy node.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next,*bottom;Node(intnewdata){data=newdata;next=bottom=nullptr;}};// comparator function for priority queuestructmycomp{booloperator()(Node*a,Node*b){returna->data>b->data;}};// function to flatten the given linked listNode*flatten(Node*root){priority_queue<Node*,vector<Node*>,mycomp>pq;Node*head=nullptr;Node*tail=nullptr;// pushing main link nodes into priority_queuewhile(root!=nullptr){pq.push(root);root=root->next;}// Extracting the minimum node// while priority queue is not emptywhile(!pq.empty()){// extracting minautominNode=pq.top();pq.pop();if(head==nullptr){head=minNode;tail=minNode;}else{tail->bottom=minNode;tail=tail->bottom;}// If we have another node at the bottom of the// popped node, push that node into the priority// queueif(minNode->bottom){pq.push(minNode->bottom);minNode->bottom=nullptr;}}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 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;}
Java
// Java program for flattening a Linked Listimportjava.util.PriorityQueue;classNode{intdata;Nodenext,bottom;Node(intnewData){data=newData;next=bottom=null;}}// Comparator class for the priority queueclassNodeComparatorimplementsjava.util.Comparator<Node>{@Overridepublicintcompare(Nodea,Nodeb){returnInteger.compare(a.data,b.data);}}// Function to flatten the linked listclassGfG{staticNodeflatten(Noderoot){// Create a priority queue with custom comparatorPriorityQueue<Node>pq=newPriorityQueue<>(newNodeComparator());Nodehead=null;Nodetail=null;// Pushing main link nodes into the priority_queue.while(root!=null){pq.add(root);root=root.next;}// Extracting the minimum node while the priority// queue is not emptywhile(!pq.isEmpty()){// Extracting minNodeminNode=pq.poll();if(head==null){head=minNode;tail=minNode;}else{tail.bottom=minNode;tail=tail.bottom;}// If we have another node at the bottom of the// popped node, push that node into the priority queueif(minNode.bottom!=null){pq.add(minNode.bottom);minNode.bottom=null;}}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 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
# Python program for flattening a Linked Listfromheapqimportheappush,heappopclassNode:def__init__(self,data):self.data=dataself.next=self.bottom=None# Utility function to insert a node at beginning# of the linked listdefpush(head,data):# 1 & 2: Allocate the Node & Put in the datanewNode=Node(data)# Make next of newNode as headnewNode.bottom=head# Move the head to point to newNodehead=newNode# Return to link it backreturnheaddefprintList(node):whilenodeisnotNone:print(f"{node.data}",end="")ifnode.bottomisnotNone:print(" -> ",end="")node=node.bottomprint()# Class to compare two node objectsclassCmp:def__init__(self,node):self.node=nodedef__lt__(self,other):returnself.node.data<other.node.datadefflatten(root):pq=[]head=Nonetail=None# Pushing main link nodes into priority_queuewhileroot:heappush(pq,Cmp(root))root=root.next# Extracting the minimum node while the priority # queue is not emptywhilepq:minNode=heappop(pq).nodeifheadisNone:head=minNodetail=minNodeelse:tail.bottom=minNodetail=tail.bottom# If we have another node at the bottom of the popped # node, push that node into the priority queueifminNode.bottom:heappush(pq,Cmp(minNode.bottom))minNode.bottom=Nonereturnheadif__name__=='__main__':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#
// C# implementation for above approachusingSystem;usingSystem.Collections.Generic;publicclassNode{publicintData;publicNodeNext;publicNodeBottom;publicNode(intnewData){Data=newData;Next=null;Bottom=null;}}// Comparator class for the priority queuepublicclassNodeComparer:IComparer<Node>{publicintCompare(Nodea,Nodeb){returna.Data.CompareTo(b.Data);}}classGfG{staticNodeFlatten(Noderoot){// Priority queue (min-heap) using a sorted list for// simplicitySortedList<int,Node>pq=newSortedList<int,Node>();Nodehead=null;Nodetail=null;// Push main link nodes into the priority queuewhile(root!=null){pq.Add(root.Data,root);root=root.Next;}// Extracting the minimum node while priority queue// is not emptywhile(pq.Count>0){// Extracting minNodeminNode=pq.Values[0];pq.RemoveAt(0);if(head==null){head=minNode;tail=minNode;}else{tail.Bottom=minNode;tail=tail.Bottom;}// If we have another node at the bottom of the// popped node, push that node into the priority// queueif(minNode.Bottom!=null){pq.Add(minNode.Bottom.Data,minNode.Bottom);minNode.Bottom=null;}}returnhead;}staticvoidPrintList(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 | | | 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);}}
JavaScript
// Javascript implementation for above approachclassNode{constructor(data){this.data=data;this.next=null;this.bottom=null;}}// Comparator function for the priority queueclassMinHeap{constructor(){this.heap=[];}push(node){this.heap.push(node);this._heapifyUp(this.heap.length-1);}pop(){if(this.size()===0)returnnull;constroot=this.heap[0];constlast=this.heap.pop();if(this.size()>0){this.heap[0]=last;this._heapifyDown(0);}returnroot;}size(){returnthis.heap.length;}_heapifyUp(index){constparentIndex=Math.floor((index-1)/2);if(index>0&&this.heap[index].data<this.heap[parentIndex].data){[this.heap[index],this.heap[parentIndex]]=[this.heap[parentIndex],this.heap[index]];this._heapifyUp(parentIndex);}}_heapifyDown(index){constleftChildIndex=2*index+1;constrightChildIndex=2*index+2;letsmallest=index;if(leftChildIndex<this.size()&&this.heap[leftChildIndex].data<this.heap[smallest].data){smallest=leftChildIndex;}if(rightChildIndex<this.size()&&this.heap[rightChildIndex].data<this.heap[smallest].data){smallest=rightChildIndex;}if(smallest!==index){[this.heap[index],this.heap[smallest]]=[this.heap[smallest],this.heap[index]];this._heapifyDown(smallest);}}}functionflatten(root){constpq=newMinHeap();lethead=null;lettail=null;// Push main linked list nodes into the priority queuewhile(root!==null){pq.push(root);root=root.next;}// Extracting the minimum node while priority queue is// not emptywhile(pq.size()>0){constminNode=pq.pop();if(head===null){head=minNode;tail=minNode;}else{tail.bottom=minNode;tail=tail.bottom;}// If we have another node at the bottom of the// popped node, push that node into the priority// queueif(minNode.bottom!==null){pq.push(minNode.bottom);minNode.bottom=null;}}returnhead;}functionprintList(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*/// Driver Codelethead=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);