Javascript 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:
Javascript
<script>
var head;
class Node
{
constructor(val)
{
this .data = val;
this .down = null ;
this .next = null ;
}
}
function merge(a, b)
{
if (a == null )
return b;
if (b == null )
return a;
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)
{
if (root == null ||
root.right == null )
return root;
root.right = flatten(root.right);
root = merge(root, root.right);
return root;
}
function push(head_ref, data)
{
var new_node = new Node(data);
new_node.down = head_ref;
head_ref = new_node;
return head_ref;
}
function printList()
{
var temp = head;
while (temp != null )
{
document.write(temp.data + " " );
temp = temp.down;
}
document.write();
}
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);
head = flatten(head);
printList();
</script>
|
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!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...