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 next and to the node before it with prev. Here each node also has a child pointer, which is either null or leads to the first node of another doubly linked list. That list's nodes may have children of their own, so the lists form several levels. Given the head of the top list, rearrange the pointers so that all nodes sit in one doubly linked list. A node's child list must come right after the node and before the node's old next. Every child pointer must end up null. Return the head.

Example 1
Input: 1 - 2 - 3 - 4 - 5 - 6, where 3 has child 7 - 8 - 9 - 10, and 8 has child 11 - 12
Output: 1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6
Example 2
Input: 1 - 2, where 1 has child 3
Output: 1, 3, 2
Solution

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 arrow goes down from 3 to the child list 7, 8, 9, 10, and another goes from 8 to 11, 12. The answer, 1, 2, 3, 7, 8, 11, 12, 9, 10, 4, 5, 6, reads each child list at the point where its arrow leaves.

Before: the main list 1 to 6, with node 3 pointing down to the child list 7 to 10, whose last node 10 is the tail, and node 8 pointing down to 11 and 12. After splicing at node 3: 1, 2, 3, 7, 8, 9, 10, 4, 5, 6 on one level, with 11 and 12 still below 8.

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 next from the child's first node until there is no next. Then two places need new links, each in both directions. At the end of the child list, the tail's next becomes the node's old next, and that old next's prev becomes the tail. At the start, the node's next becomes the child's first node, and that node's prev becomes the node.

The order of these updates matters. The node's old next must be linked to the tail before the node's next is changed to the child, or the reference to the old next is lost. Last, the node's child is set to null, as the problem asks.

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 next simply becomes null, which is right, but there is no old next whose prev could be set. That one update needs a null check.

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 works in these steps:

  1. Walk the list from head with a variable node, moving to node.next each time. A node whose child is null needs nothing, so the loop skips it.
  2. At a node with a child, keep the child list's first node in child. Start a variable tail there, and move it along next until it reaches the last node of the child list.
  3. Link the end of the child list: set tail.next to node.next, and, if that old next is not null, set its prev to tail.
  4. Link the start: set node.next to child and child.prev to node. Then set node.child to null. The loop continues into the spliced list.
  5. When the walk falls off the end, return head. The head never changes, because splices only insert nodes after it.

The class also has a small Node class and three helpers. level builds one plain list, and at finds a node on a level to hang a child list on. show prints the result forward along next, then backward along prev. The main method runs both examples, a child on the last node of the main list, a child that has its own child, and an empty list.

Java
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:

Output
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 prev pointer was fixed along with next. The second line, 1, 3, 2, is example 2.

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) test, the program prints the first two lines and then stops with 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, child and tail, with no recursion and no stack, however deep the levels go.

A tree can be flattened into a list too: see Flatten Binary Tree to Linked List.