Given a list that can grow in both horizontal and vertical directions (right and down), flatten it into a singly linked list. The conversion should be in such a way that the down node should be processed before the next node for any node.

A multilevel list is similar to the standard linked list except it has an extra field, down, which points to a vertical list. The vertical list can have a horizontal list attached to it and vice versa.

 
For example, consider the following linked list:

Flatten List

The flattened list would be:

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> 11 -> 12 -> 13 -> 14 -> 15 -> null

 
We can use recursion to flatten a multilevel list. The idea is to recursively flatten the given linked list by recursively flattening the down list first, followed by the next list. The flattened down list for a node is linked to the next pointer of that node, while the flattened next list for a node is linked to the next pointer of the last seen node.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The original list is :
1 [ 2 [ 3 ]] 4 [ 5 [ 6 [ 7 8 ]] 9 10 [ 11 [ 12 ] 13 ]] 14 15
 
The flattened list is :
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> 11 -> 12 -> 13 -> 14 -> 15 -> null

The time complexity of the above solution is O(n) and requires O(n) space for the call stack. We can further optimize the code by maintaining a tail pointer as we move along. This approach is demonstrated here.