Flattening a Linked List
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 45Output: 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 30Output: 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
- After merging the current linked list with the next linked list, return the head node of the current linked list
Below is the implementation of the above approach:
C++
// C++ program for flattening a Linked List #include <bits/stdc++.h> using namespace std; // Linked list node class Node { public : int data; Node *right, *down; }; Node* head = NULL; // An utility function to merge two sorted // linked lists Node* merge(Node* a, Node* b) { // If first linked list is empty then second // is the answer if (a == NULL) return b; // If second linked list is empty then first // is the result if (b == NULL) return a; // Compare the data members of the two linked // lists and put the larger one in the result Node* result; if (a->data < b->data) { result = a; result->down = merge(a->down, b); } else { result = b; result->down = merge(a, b->down); } result->right = NULL; return result; } Node* flatten(Node* root) { // Base Cases if (root == NULL || root->right == NULL) return root; // Recur for list on right root->right = flatten(root->right); // Now merge root = merge(root, root->right); // Return the root // it will be in turn merged with its left return root; } // Utility function to insert a node at // beginning of the linked list Node* push(Node* head_ref, int data) { // Allocate the Node & Put in the data Node* new_node = new Node(); new_node->data = data; new_node->right = NULL; // Make next of new Node as head new_node->down = head_ref; // Move the head to point to new Node head_ref = new_node; return head_ref; } void printList() { Node* temp = head; while (temp != NULL) { cout << temp->data << " " ; temp = temp->down; } cout << endl; } // Driver's code int main() { /* Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ head = push(head, 30); head = push(head, 8); head = push(head, 7); head = push(head, 5); head->right = push(head->right, 20); head->right = push(head->right, 10); head->right->right = push(head->right->right, 50); head->right->right = push(head->right->right, 22); head->right->right = push(head->right->right, 19); head->right->right->right = push(head->right->right->right, 45); head->right->right->right = push(head->right->right->right, 40); head->right->right->right = push(head->right->right->right, 35); head->right->right->right = push(head->right->right->right, 20); // Function call head = flatten(head); printList(); return 0; } // This code is contributed by rajsanghavi9. |
Java
// Java program for flattening a Linked List class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node right, down; Node( int data) { this .data = data; right = null ; down = null ; } } // An utility function to merge two sorted linked lists Node merge(Node a, Node b) { // if first linked list is empty then second // is the answer if (a == null ) return b; // if second linked list is empty then first // is the result if (b == null ) return a; // compare the data members of the two linked lists // and put the larger one in the result Node result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null ; return result; } Node flatten(Node root) { // Base Cases if (root == null || root.right == null ) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* Utility function to insert a node at beginning of the linked list */ Node push(Node head_ref, int data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /*5. return to link it back */ return head_ref; } void printList() { Node temp = head; while (temp != null ) { System.out.print(temp.data + " " ); temp = temp.down; } System.out.println(); } // Driver's code public static void main(String args[]) { LinkedList L = new LinkedList(); /* Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ L.head = L.push(L.head, 30 ); L.head = L.push(L.head, 8 ); L.head = L.push(L.head, 7 ); L.head = L.push(L.head, 5 ); L.head.right = L.push(L.head.right, 20 ); L.head.right = L.push(L.head.right, 10 ); L.head.right.right = L.push(L.head.right.right, 50 ); L.head.right.right = L.push(L.head.right.right, 22 ); L.head.right.right = L.push(L.head.right.right, 19 ); L.head.right.right.right = L.push(L.head.right.right.right, 45 ); L.head.right.right.right = L.push(L.head.right.right.right, 40 ); L.head.right.right.right = L.push(L.head.right.right.right, 35 ); L.head.right.right.right = L.push(L.head.right.right.right, 20 ); // Function call L.head = L.flatten(L.head); L.printList(); } } /* This code is contributed by Rajat Mishra */ |
Python3
# Python3 program for flattening a Linked List class Node(): def __init__( self , data): self .data = data self .right = None self .down = None class LinkedList(): def __init__( self ): # head of list self .head = None # Utility function to insert a node at beginning of the # linked list def push( self , head_ref, data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(data) # Make next of new Node as head new_node.down = head_ref # 4. Move the head to point to new Node head_ref = new_node # 5. return to link it back return head_ref def printList( self ): temp = self .head while (temp ! = None ): print (temp.data, end = " " ) temp = temp.down print () # An utility function to merge two sorted linked lists def merge( self , a, b): # if first linked list is empty then second # is the answer if (a = = None ): return b # if second linked list is empty then first # is the result if (b = = None ): return a # compare the data members of the two linked lists # and put the larger one in the result result = None if (a.data < b.data): result = a result.down = self .merge(a.down, b) else : result = b result.down = self .merge(a, b.down) result.right = None return result def flatten( self , root): # Base Case if (root = = None or root.right = = None ): return root # recur for list on right root.right = self .flatten(root.right) # now merge root = self .merge(root, root.right) # return the root # it will be in turn merged with its left return root # Driver's code if __name__ = = '__main__' : L = LinkedList() ''' Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 ''' L.head = L.push(L.head, 30 ) L.head = L.push(L.head, 8 ) L.head = L.push(L.head, 7 ) L.head = L.push(L.head, 5 ) L.head.right = L.push(L.head.right, 20 ) L.head.right = L.push(L.head.right, 10 ) L.head.right.right = L.push(L.head.right.right, 50 ) L.head.right.right = L.push(L.head.right.right, 22 ) L.head.right.right = L.push(L.head.right.right, 19 ) L.head.right.right.right = L.push(L.head.right.right.right, 45 ) L.head.right.right.right = L.push(L.head.right.right.right, 40 ) L.head.right.right.right = L.push(L.head.right.right.right, 35 ) L.head.right.right.right = L.push(L.head.right.right.right, 20 ) # Function call L.head = L.flatten(L.head) L.printList() # This code is contributed by maheshwaripiyush9 |
C#
// C# program for flattening a Linked List using System; public class List { Node head; // head of list /* Linked list Node */ public class Node { public int data; public Node right, down; public Node( int data) { this .data = data; right = null ; down = null ; } } // An utility function to merge two sorted linked lists Node merge(Node a, Node b) { // if first linked list is empty then second // is the answer if (a == null ) return b; // if second linked list is empty then first // is the result if (b == null ) return a; // compare the data members of the two linked lists // and put the larger one in the result Node result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null ; return result; } Node flatten(Node root) { // Base Cases if (root == null || root.right == null ) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* * Utility function to insert a node at beginning * of the linked list */ Node Push(Node head_ref, int data) { /* * 1 & 2: Allocate the Node & Put in the data */ Node new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /* 5. return to link it back */ return head_ref; } void printList() { Node temp = head; while (temp != null ) { Console.Write(temp.data + " " ); temp = temp.down; } Console.WriteLine(); } // Driver's code public static void Main(String[] args) { List L = new List(); /* * Let us create the following linked list 5 -> 10 * -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V * V 8 50 40 | | V V 30 45 */ L.head = L.Push(L.head, 30); L.head = L.Push(L.head, 8); L.head = L.Push(L.head, 7); L.head = L.Push(L.head, 5); L.head.right = L.Push(L.head.right, 20); L.head.right = L.Push(L.head.right, 10); L.head.right.right = L.Push(L.head.right.right, 50); L.head.right.right = L.Push(L.head.right.right, 22); L.head.right.right = L.Push(L.head.right.right, 19); L.head.right.right.right = L.Push(L.head.right.right.right, 45); L.head.right.right.right = L.Push(L.head.right.right.right, 40); L.head.right.right.right = L.Push(L.head.right.right.right, 35); L.head.right.right.right = L.Push(L.head.right.right.right, 20); // Function call L.head = L.flatten(L.head); L.printList(); } } // This code is contributed by umadevi9616 |
Javascript
// javascript program for flattening a Linked List var head; // head of list /* Linked list Node */ class Node { constructor(val) { this .data = val; this .down = null ; this .next = null ; } } // An utility function to merge two sorted linked lists function merge(a, b) { // if first linked list is empty then second // is the answer if (a == null ) return b; // if second linked list is empty then first // is the result if (b == null ) return a; // compare the data members of the two linked lists // and put the larger one in the result var result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null ; return result; } function flatten(root) { // Base Cases if (root == null || root.right == null ) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* * Utility function to insert a node at beginning of the linked list */ function push(head_ref , data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /* 5. return to link it back */ return head_ref; } function printList() { var temp = head; while (temp != null ) { document.write(temp.data + " " ); temp = temp.down; } document.write(); } /* Driver program to test above functions */ /* * Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 * 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ head = push(head, 30); head = push(head, 8); head = push(head, 7); head = push(head, 5); head.right = push(head.right, 20); head.right = push(head.right, 10); head.right.right = push(head.right.right, 50); head.right.right = push(head.right.right, 22); head.right.right = push(head.right.right, 19); head.right.right.right = push(head.right.right.right, 45); head.right.right.right = push(head.right.right.right, 40); head.right.right.right = push(head.right.right.right, 35); head.right.right.right = push(head.right.right.right, 20); // flatten the list head = flatten(head); printList(); // This code contributed by aashish1995 |
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 <bits/stdc++.h> 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<Node*, vector<Node*>, 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<Node> { @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<Node> pq = new PriorityQueue<Node>( 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); } } |
Python3
from heapq import heappush, heappop class Node: def __init__( self , d): self .data = d self .right = self .down = None class LinkedList(): def __init__( self ): # head of list self .head = None # Utility function to insert a node at beginning of the # linked list def push( self , head_ref, data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(data) # Make next of new Node as head new_node.down = head_ref # 4. Move the head to point to new Node head_ref = new_node # 5. return to link it back return head_ref def printList( self ): temp = self .head while (temp ! = None ): print (temp.data, end = " " ) temp = temp.down print () # class to compare two node objects class Cmp : def __init__( self , node): self .node = node def __lt__( self , other): return self .node.data < other.node.data def flatten(root): pq = [] # push main linked list nodes to priority queue while root: heappush(pq, Cmp (root)) root = root.right dummy = Node( 0 ) temp = dummy # keep popping out the min node until there are no nodes left in priority queue while pq: node = heappop(pq).node temp.down = node temp = node # if bottom child exist add it to priority queue if node.down: heappush(pq, Cmp (node.down)) return dummy.down if __name__ = = '__main__' : L = LinkedList() ''' Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 ''' L.head = L.push(L.head, 30 ) L.head = L.push(L.head, 8 ) L.head = L.push(L.head, 7 ) L.head = L.push(L.head, 5 ) L.head.right = L.push(L.head.right, 20 ) L.head.right = L.push(L.head.right, 10 ) L.head.right.right = L.push(L.head.right.right, 50 ) L.head.right.right = L.push(L.head.right.right, 22 ) L.head.right.right = L.push(L.head.right.right, 19 ) L.head.right.right.right = L.push(L.head.right.right.right, 45 ) L.head.right.right.right = L.push(L.head.right.right.right, 40 ) L.head.right.right.right = L.push(L.head.right.right.right, 35 ) L.head.right.right.right = L.push(L.head.right.right.right, 20 ) flatten(L.head) L.printList() |
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<Node> { 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<Node>( 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<T> { private List<T> queue; private IComparer<T> comparer; public PriorityQueue(IComparer<T> comparer) { queue = new List<T>(); 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. |
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.
Please Login to comment...