GFG App
Open App
Browser
Continue

Given a linked list where every node represents a linked list and contains two pointers of its type:

• Pointer to next node in the main list (we call it ‘right’ pointer in the code below)
• Pointer to a linked list where this node is headed (we call it the ‘down’ pointer in the code below).

Note: All linked lists are sorted and the resultant linked list should also be sorted

Examples:

Input:    5 -> 10 -> 19 -> 28
|        |         |        |
V       V       V       V
7      20      22     35
|                 |        |
V               V       V
8               50     40
|                          |
V                        V
30                       45

Output: 5->7->8->10->19->20->22->28->30->35->40->45->50

Input:    3 -> 10 -> 7 -> 14
|        |         |        |
V       V       V       V
9      47      15     22
|                 |
V                V
17              30

Output: 3->7->9->10->14->15->17->22->30->47

The idea is to use the Merge() process of merge sort for linked lists. Use merge() to merge lists one by one, recursively merge() the current list with the already flattened list. The down pointer is used to link nodes of the flattened list.

Follow the given steps to solve the problem:

• Recursively call to merge the current linked list with the next linked list
• If the current linked list is empty or there is no next linked list then return the current linked list (Base Case)
• Start merging the linked lists, starting from the last linked list

Below is the implementation of the above approach:

## Javascript

Output

5 7 8 10 19 20 20 22 30 35 40 45 50

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

Auxiliary Space: O(1)
Explanation: As we are merging 2 lists at a time,

• 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).
• Then we will merge another list -> time = O(3M + M).
• 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
• Using arithmetic sum formula: time = O((N * N + N – 2) * M/2)
• The above expression is roughly equal to O(N * N * M) for a large value of N

Auxiliary Space: O(N*M) – because of the recursion. The recursive functions will use a recursive stack of a size equivalent to a total number of elements in the lists, which is N*M.

## Flattening a Linked List using Priority Queues:

The idea is, to build a Min-Heap and push head node of every linked list into it and then use Extract-min function to get minimum element from priority queue and then move forward in that linked list.

Follow the given steps to solve the problem:

• Create a priority queue(Min-Heap) and push the head node of every linked list into it
• While the priority queue is not empty, extract the minimum value node from it and if there is a next node linked to the minimum value node then push it into the priority queue
• Also, print the value of the node every time after extracting the minimum value node

Below is the implementation of the above approach:

## C++

 // C++ code for the above approach #include using namespace std;   // Linked list Node struct Node {     int data;     struct Node* next;     struct Node* bottom;       Node(int x)     {         data = x;         next = NULL;         bottom = NULL;     } };   // comparator function for priority queue struct mycomp {     bool operator()(Node* a, Node* b)     {         return a->data > b->data;     } };   void flatten(Node* root) {     priority_queue, mycomp> p;     // pushing main link nodes into priority_queue.     while (root != NULL) {         p.push(root);         root = root->next;     }       // Extracting the minimum node     // while priority queue is not empty     while (!p.empty()) {           // extracting min         auto k = p.top();         p.pop();           // printing  least element         cout << k->data << " ";         if (k->bottom)             p.push(k->bottom);     } }   // Driver's code int main(void) {     // This code builds the flattened linked list     // of first picture in this article ;     Node* head = new Node(5);     auto temp = head;     auto bt = head;     bt->bottom = new Node(7);     bt->bottom->bottom = new Node(8);     bt->bottom->bottom->bottom = new Node(30);     temp->next = new Node(10);       temp = temp->next;     bt = temp;     bt->bottom = new Node(20);     temp->next = new Node(19);     temp = temp->next;     bt = temp;     bt->bottom = new Node(22);     bt->bottom->bottom = new Node(50);     temp->next = new Node(28);     temp = temp->next;     bt = temp;     bt->bottom = new Node(35);     bt->bottom->bottom = new Node(40);     bt->bottom->bottom->bottom = new Node(45);       // Function call     flatten(head);     cout << endl;     return 0; } // this code is contributed by user_990i

## Java

 import java.util.PriorityQueue;   // Node class class Node {     int data;     Node next;     Node bottom;     Node(int data)     {         this.data = data;         next = null;         bottom = null;     } }   // Comparator class to sort nodes in a priority queue class NodeComparator implements java.util.Comparator {     @Override public int compare(Node a, Node b)     {         return a.data - b.data;     } }   public class Main {     // Function to flatten the linked list     public static void flatten(Node root)     {           // Priority queue to store nodes         PriorityQueue pq             = new PriorityQueue(new NodeComparator());           // Adding main linked list nodes into priority queue         while (root != null) {             pq.add(root);             root = root.next;         }           // Extracting the minimum node         // while priority queue is not empty         while (!pq.isEmpty()) {             // Extracting the minimum node             Node k = pq.poll();               // Printing the node data             System.out.print(k.data + " ");             if (k.bottom != null) {                 pq.add(k.bottom);             }         }     }       public static void main(String[] args)     {         Node head = new Node(5);         Node temp = head;         Node bt = head;           bt.bottom = new Node(7);         bt.bottom.bottom = new Node(8);         bt.bottom.bottom.bottom = new Node(30);           temp.next = new Node(10);         temp = temp.next;           bt = temp;         bt.bottom = new Node(20);           temp.next = new Node(19);         temp = temp.next;           bt = temp;         bt.bottom = new Node(22);         bt.bottom.bottom = new Node(50);           temp.next = new Node(28);         temp = temp.next;           bt = temp;         bt.bottom = new Node(35);         bt.bottom.bottom = new Node(40);         bt.bottom.bottom.bottom = new Node(45);           // Calling function to flatten the linked list         flatten(head);     } }

## C#

 // C# implementation for above approach using System; using System.Collections.Generic;   // Linked list Node public class Node {   public int data;   public Node next;   public Node bottom;     public Node(int x) {     data = x;     next = null;     bottom = null;   } }   // comparator function for priority queue public class MyComp : IComparer {   public int Compare(Node a, Node b) {     return a.data.CompareTo(b.data);   } }   public class Program {   public static void Flatten(Node root) {     var p = new PriorityQueue(new MyComp());     // pushing main link nodes into priority_queue.     while (root != null) {       p.Push(root);       root = root.next;     }       // Extracting the minimum node     // while priority queue is not empty     while (!p.Empty()) {         // extracting min       var k = p.Top();       p.Pop();         // printing least element       Console.Write(k.data + " ");       if (k.bottom != null)         p.Push(k.bottom);     }   }     // Priority Queue implementation   public class PriorityQueue {     private List queue;     private IComparer comparer;       public PriorityQueue(IComparer comparer) {       queue = new List();       this.comparer = comparer;     }       public void Push(T element) {       queue.Add(element);       Sort();     }       public T Pop() {       var element = queue[0];       queue.RemoveAt(0);       return element;     }       public T Top() {       return queue[0];     }       public int Size() {       return queue.Count;     }       public bool Empty() {       return queue.Count == 0;     }       private void Sort() {       queue.Sort(comparer);     }   }     // Driver's code   public static void Main() {     // This code builds the flattened linked list     // of first picture in this article ;     var head = new Node(5);     var temp = head;     var bt = head;     bt.bottom = new Node(7);     bt.bottom.bottom = new Node(8);     bt.bottom.bottom.bottom = new Node(30);     temp.next = new Node(10);       temp = temp.next;     bt = temp;     bt.bottom = new Node(20);     temp.next = new Node(19);     temp = temp.next;     bt = temp;     bt.bottom = new Node(22);     bt.bottom.bottom = new Node(50);     temp.next = new Node(28);     temp = temp.next;     bt = temp;     bt.bottom = new Node(35);     bt.bottom.bottom = new Node(40);     bt.bottom.bottom.bottom = new Node(45);       // Function call     Flatten(head);     Console.WriteLine();   } }   // This code is contributed by Amit Mangal.

## Javascript

 // JavaScript code for the above approach   // Linked list Node class Node {     constructor(x) {         this.data = x;         this.next = null;         this.bottom = null;     } }   // comparator function for priority queue function mycomp(a, b) {     return a.data > b.data; }   function flatten(root) {   const p = new PriorityQueue((a, b) => a.data - b.data);     // pushing main link nodes into priority_queue.   while (root != null) {     p.push(root);     root = root.next;   }     // Extracting the minimum node   // while priority queue is not empty   while (p.length !== 0) {     // extracting min     const k = p.pop();     // printing least element   if (k !== undefined) {     process.stdout.write(`\${k.data} `);       if (k.bottom) p.push(k.bottom);   }     } }     class PriorityQueue {   constructor(comparator = (a, b) => a - b) {     this.heap = [];     this.comparator = comparator;   }     get size() {     return this.heap.length;   }     isEmpty() {     return this.size === 0;   }     peek() {     return this.heap[0];   }     push(...values) {     values.forEach(value => {       this.heap.push(value);       this.bubbleUp(this.heap.length - 1);     });   }     pop() {     const root = this.heap[0];     const last = this.heap.pop();       if (this.size > 0) {       this.heap[0] = last;       this.bubbleDown(0);     }       return root;   }     bubbleUp(index) {     while (index > 0) {       const parent = (index - 1) >> 1;         if (this.comparator(this.heap[index], this.heap[parent]) < 0) {         [this.heap[index], this.heap[parent]] = [this.heap[parent], this.heap[index]];         index = parent;       } else {         break;       }     }   }     bubbleDown(index) {     const last = this.heap.length - 1;       while (true) {       const left = (index << 1) + 1;       const right = left + 1;       let min = index;         if (left <= last && this.comparator(this.heap[left], this.heap[min]) < 0) {         min = left;       }         if (right <= last && this.comparator(this.heap[right], this.heap[min]) < 0) {         min = right;       }         if (min !== index) {         [this.heap[index], this.heap[min]] = [this.heap[min], this.heap[index]];         index = min;       } else {         break;       }     }   } }   // Driver's code (function main() {     // This code builds the flattened linked list     // of first picture in this article ;     let head = new Node(5);     let temp = head;     let bt = head;     bt.bottom = new Node(7);     bt.bottom.bottom = new Node(8);     bt.bottom.bottom.bottom = new Node(30);     temp.next = new Node(10);       temp = temp.next;     bt = temp;     bt.bottom = new Node(20);     temp.next = new Node(19);     temp = temp.next;     bt = temp;     bt.bottom = new Node(22);     bt.bottom.bottom = new Node(50);     temp.next = new Node(28);     temp = temp.next;     bt = temp;     bt.bottom = new Node(35);     bt.bottom.bottom = new Node(40);     bt.bottom.bottom.bottom = new Node(45);       // Function call     flatten(head);     console.log(); })();   // This code is contributed by Amit Mangal.

Output

5 7 8 10 19 20 22 28 30 35 40 45 50

Time Complexity: O(N * M * log(N)) – where N is the no of nodes in the main linked list (reachable using the next pointer) and M is the no of nodes in a single sub-linked list (reachable using a bottom pointer).
Auxiliary Space: O(N) – where N is the no of nodes in the main linked list (reachable using the next pointer).

NOTE: In the above explanation, k means the Node which contains the minimum element.

My Personal Notes arrow_drop_up