Flatten a Multilevel Doubly Linked List
Fold every child list into the main list, right after the node it hangs from, so the whole structure becomes one level.
In a doubly linked list, each node points to the node after it with nextprevchildnextchild
Example 1
Output: 1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6
Example 2
Output: 1, 3, 2
The Idea
Think of a document outline. Point 3 has sub-points 7 to 10 under it, and sub-point 8 has its own sub-points 11 and 12. Printed as one flat list, every point is followed by everything under it, and only then by the next point on its own level. Flattening the list asks for exactly that order.
Look at the top half of the picture below, labelled "Before". The top row is the main list, 1 to 6. A dashed child
So how do we move a whole child list up into the main list? Take node 3, labelled "node" in the picture. Its old next is 4, and the last node of its child list is 10, labelled "tail". If 3 now points on to 7, and 10 points on to 4, the child list sits between them. That is the bottom half of the picture: four nodes moved up a level by changing a few pointers. Inserting a list into another this way is called splicing.
Notice what the splice did not do. The list 11, 12 still hangs below 8. But 8 is now part of the main list, so a walk along the main list will reach 8 a little later and splice 11, 12 in the same way. Deeper levels need no special handling: one walk from the head, splicing at each node that has a child, flattens everything.
Solution Approach
Turning that idea into code means settling four things: why one walk beats a method that calls itself for each child list, which pointers a splice changes, what to do when a node with a child is last in its list, and why deeper levels need no extra work.
Walking instead of recursing
Is there a more obvious way? Visiting a node, then everything under it, then the rest is called a depth-first order. A recursive method gives it directly: at a node with a child, it calls itself to flatten the child list, then carries on. It works, but every level of nesting leaves one more unfinished call waiting in memory, so a very deep list needs memory in proportion to its depth. Splicing during one walk keeps only a few variables, however deep the levels go.
The four pointers of a splice
Which links have to change? Before a splice, the walk finds the tail of the child list by following nextnextprevnextprev
The order of these updates matters. The node's old next must be linked to the tail before the node's nextchild
A child on a node with no next
What if the node with a child is the last node of its list, like 2 in 1 - 2, where 2 has child 3 - 4? Then the old next is null. The tail's nextprev
Deeper levels
Why is one walk enough? After a splice, the walk goes on with the node's new next, which is the first node of the child list it just moved up. So it walks through that child list too, and splices any child it meets there before reaching the node's old next. Each level is handled when the walk arrives at it, which also gives the required order.
Java Solution
The method flatten
- Walk the list from
with a variablehead , moving tonode each time. A node whosenode.next is null needs nothing, so the loop skips it.child - At a node with a child, keep the child list's first node in
. Start a variablechild there, and move it alongtail until it reaches the last node of the child list.next - Link the end of the child list: set
totail.next , and, if that old next is not null, set itsnode.next toprev .tail - Link the start: set
tonode.next andchild tochild.prev . Then setnode to null. The loop continues into the spliced list.node.child - When the walk falls off the end, return
. The head never changes, because splices only insert nodes after it.head
The class also has a small Nodelevelatshownextprevmain
public class FlattenMultilevelDoublyLinkedList {
static class Node {
int val;
Node prev;
Node next;
Node child;
Node(int val) {
this.val = val;
}
}
public static Node flatten(Node head) {
for (Node node = head; node != null; node = node.next) {
if (node.child == null) {
continue; // nothing hangs below this node
}
Node child = node.child;
Node tail = child;
while (tail.next != null) {
tail = tail.next; // last node of the child list
}
tail.next = node.next; // child list's end -> old next
if (node.next != null) {
node.next.prev = tail;
}
node.next = child; // node -> child list's start
child.prev = node;
node.child = null;
}
return head;
}
// Builds one level: a plain doubly linked list of the given values.
static Node level(int... vals) {
Node head = null, last = null;
for (int v : vals) {
Node n = new Node(v);
if (head == null) {
head = n;
} else {
last.next = n;
n.prev = last;
}
last = n;
}
return head;
}
// Finds the node with this value on one level, to hang a child list on it.
static Node at(Node head, int val) {
while (head.val != val) {
head = head.next;
}
return head;
}
// Prints the list forward with next, then backward with prev.
static String show(Node head) {
if (head == null) {
return "(empty)";
}
StringBuilder fwd = new StringBuilder(), back = new StringBuilder();
Node last = head;
for (Node n = head; n != null; n = n.next) {
fwd.append(fwd.length() == 0 ? "" : ", ").append(n.val);
last = n;
}
for (Node n = last; n != null; n = n.prev) {
back.append(back.length() == 0 ? "" : ", ").append(n.val);
}
return fwd + " (backward: " + back + ")";
}
public static void main(String[] args) {
Node top = level(1, 2, 3, 4, 5, 6);
Node mid = level(7, 8, 9, 10);
at(top, 3).child = mid;
at(mid, 8).child = level(11, 12);
System.out.println(show(flatten(top)));
Node ex2 = level(1, 2);
ex2.child = level(3);
System.out.println(show(flatten(ex2)));
Node lastHasChild = level(1, 2);
at(lastHasChild, 2).child = level(3, 4);
System.out.println(show(flatten(lastHasChild)));
Node chain = level(1, 2);
chain.child = level(3);
chain.child.child = level(4);
System.out.println(show(flatten(chain)));
System.out.println(show(flatten(null)));
}
}
Running it prints:
1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6 (backward: 6, 5, 4, 10, 9, 12, 11, 8, 7, 3, 2, 1)
1, 3, 2 (backward: 2, 3, 1)
1, 2, 3, 4 (backward: 4, 3, 2, 1)
1, 3, 4, 2 (backward: 2, 4, 3, 1)
(empty)
Look at the first line, from example 1: after 3 come 7 and 8, then 11 and 12 from the deepest level, then 9 and 10, and only then 4, 5 and 6. Its backward part, 6, 5, 4, 10, 9, 12, 11, 8, 7, 3, 2, 1, is the same order reversed, so every prevnext
The third line comes from 1 - 2, where 2 has child 3 - 4, and reads 1, 2, 3, 4 forward and 4, 3, 2, 1 backward. This is the case the null check is for. Without the if (node.next != null)NullPointerException: Cannot assign field "prev" because "<local1>.next" is null
The fourth line, 1, 3, 4, 2, comes from a list where 1 has child 3 and 3 has child 4. The splice at 1 moves 3 up, and the walk then reaches 3 and moves 4 up, before going on to 2. The last line shows that an empty list comes back empty, because the walk never starts.
Complexity
The work is the walk along the main list plus one tail search per child list.
- Time: O(n), where n is the number of nodes on all levels together. The walk ends up visiting every node once, since every child list is spliced in before the walk gets there. Each tail search walks only its own child list, before that list's children are spliced into it, so no node is walked by two tail searches.
- Space: O(1). A splice only changes pointers on nodes that already exist, and the method keeps just
,node andchild , with no recursion and no stack, however deep the levels go.tail
A tree can be flattened into a list too: see