Java Program For Flattening A Linked List
Last Updated :
13 Jun, 2022
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).
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
{
// Head of list
Node head;
// 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 code
public static void main(String args[])
{
LinkedList L = new LinkedList();
/* 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
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 main linked list (reachable using right pointer) and M is the no of node in a single sub linked list (reachable using down pointer).
Space Complexity: O(N*M) as the recursive functions will use recursive stack of size equivalent to total number of elements in the lists.
Please refer complete article on Flattening a Linked List for more details!
Similar Reads
Flattening a Linked List Given a Linked List of size n, where every node represents a sub-linked-list and contains two pointers:next pointer to the next nodebottom pointer to a linked list where this node is head.Each of the sub-linked-list is in sorted order. Flatten the Link List such that all the nodes appear in a single
15+ min read
Javascript Program For Deleting A Node In A Doubly Linked List Pre-requisite: Doubly Link List Set 1| Introduction and InsertionWrite a function to delete a given node in a doubly-linked list. Original Doubly Linked List Approach: The deletion of a node in a doubly-linked list can be divided into three main categories: After the deletion of the head node. After
4 min read
Java Program to Convert ArrayList to LinkedList Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5]
6 min read
Javascript Program For Rearranging A Given Linked List In-Place Given a singly linked list L0 -> L1 -> ⦠-> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
7 min read
Flatten a Stream of Lists in Java using forEach loop Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Li
3 min read
ArrayList vs LinkedList in Java An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. However, the limitation of the array is that the size of the array is predefined and fixed. There are multiple ways to solve this problem. In this article, the diff
5 min read