You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.

so at first glance, this is kind of a hard to understand problem, mainly because I’m not sure about the rules of flatten this strange data structure.
but on second thought, this is very much like a preorder tranverse of a tree,
so each node is like a treenode, and the prev pointer can be seen as a pointer point its father node. and we have left and right point: child and next. so we tranverse this tree starting from root node, and we iterate all the way down, if the next node have left node(child pointer) then we choose the left way, otherwise, we will go right way.

however, this problem is not exactly like preorder tranverse for trees.
because we can’t flatten this linklist using extra space, which means we need to do it in place.

so I start to implement my idea, however, the logic is messed up, so it fails.
but the solution provide by leetcode is also based on preorder tranverse. but it did have a much clear logic than me.

  1. use a pointer, start from the head, move one step each time to the next node
  2. When meet with a node with child, say node p, follow its child chain to the end and connect the tail node with p.next, by doing this we merged the child chain back to the main thread.(in a sentence: find the first node with child node)
  3. Return to p and proceed until find next node with child.
  4. Repeat until reach null
    Even though this list is pretty clear, but I don’t really understand the logic here
class Solution {
    public Node flatten(Node head) {
        if( head == null) return head;
	// Pointer
        Node p = head; 
        while( p!= null) {
            /* CASE 1: if no child, proceed */
            if( p.child == null ) {
                p = p.next; //each time p will move to the first place where p have child
                continue;
            }
            /* CASE 2: got child, find the tail of the child and link it to p.next */
            Node temp = p.child;
            // Find the tail of the child
            while( temp.next != null )  //temp will keep moving until it's next pointer is null
                temp = temp.next;
            // Connect tail with p.next, if it is not null
            temp.next = p.next;  
            if( p.next != null )  p.next.prev = temp;
            // Connect p with p.child, and remove p.child
            p.next = p.child; 
            p.child.prev = p;
            p.child = null;
        }
        return head;
    }
}