Skip to content
Related Articles

Related Articles

Improve Article

Flattening a Linked List

  • Difficulty Level : Hard
  • Last Updated : 28 Jun, 2021

Given a linked list where every node represents a linked list and contains two pointers of its type: 
(i) Pointer to next node in the main list (we call it ‘right’ pointer in the code below) 
(ii) Pointer to a linked list where this node is headed (we call it the ‘down’ pointer in the code below). 
All linked lists are sorted. See the following example  

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

Write a function flatten() to flatten the lists into a single linked list. The flattened linked list should also be sorted. For example, for the above input list, output list should be 5->7->8->10->19->20->22->28->30->35->40->45->50. 

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

Below is the implementation of the above approach:



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 program to test above functions */
    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);
  
        // flatten the list
        L.head = L.flatten(L.head);
  
        L.printList();
    }
} /* This code is contributed by Rajat Mishra */

Python3




# Python 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 program to test above functions 
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 the list
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 program to test above functions */
    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);
  
        // flatten the list
        L.head = L.flatten(L.head);
  
        L.printList();
    }
}
  
// This code is contributed by umadevi9616

Javascript




<script>
// 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 povar 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 
</script>
Output: 
5 7 8 10 19 20 20 22 30 35 40 45 50

 

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :