Given a multilevel linked list, convert it into a singly linked list so that all nodes of the first level appear first, followed by all nodes of the second level, and so on.

The multilevel linked list is similar to the simple linked list, except that it has one extra field that points to that node’s child. The child may point to a separate list altogether, which may have children of its own.

 
For example, consider the following multilevel linked list:

Multilevel Linked List

We should convert it into list 1—>2—>3—>4—>5—>6—>7—>8—>9—>10—>11—>12—>null.

 
The idea is to use the queue data structure to solve this problem. We start by traversing the list horizontally from the head node using the next pointer, and whenever a node with a child is found, insert the child node into a queue. If the end of the list is reached, dequeue the front node, set it as the next node of the last encountered node, and repeat the entire process till the queue becomes empty.

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

C++


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> null

The time complexity of the above solution is O(n), where n is the total number of nodes in the multilevel linked list, and doesn’t require any extra space.

 
The above solution requires O(n) extra space for the queue data structure. We can also solve this problem with constant space. The idea is to maintain a tail pointer that always points at the end of the current list. Like the previous approach, start by traversing the list horizontally using the next pointer. Whenever we encounter a child node, append it at the end of the list and update the tail to the last node of the child node. Repeat this process until the end of the list is reached.

This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> nullptr

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> null