package leetcode;

/**
 * https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
 */
public class Problem430 {
    private static class Node {
        public int val;
        public Node prev;
        public Node next;
        public Node child;

        public Node() {
        }

        public Node(int _val, Node _prev, Node _next, Node _child) {
            val = _val;
            prev = _prev;
            next = _next;
            child = _child;
        }
    }

    public Node flatten(Node head) {
        for (Node n = head; n != null; n = n.next) {
            if (n.child != null) {
                Node tmp = n.next;
                n.next = n.child;
                Node cn = n.child;
                while (cn.next != null) {
                    cn = cn.next;
                }
                cn.next = tmp;
            }
        }
        return head;
    }

    private static void print(Node head) {
        for (Node n = head; n != null; n = n.next) {
            System.out.print(n.val + ' ');
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Problem430 prob = new Problem430();
    }
}

@@ -469,24 +469,117 @@
 d;%0A        %7D
+%0A%0A        @Override%0A        public String toString() %7B%0A            return %22%22 + val;%0A        %7D
 %0A    %7D%0A%0A    
@@ -754,24 +754,34 @@
     
-n.next = 
+Node cn = flatten(
 n.child
+)
 ;%0A  
@@ -798,25 +798,80 @@
     
-Node cn = n.child
+n.next = cn;%0A                cn.prev = n;%0A                n.child = null
 ;%0A  
@@ -1009,321 +1009,127 @@
     
-%7D%0A
     
-    %7D%0A        return head;%0A
+if (tmp != null) %7B%0A         
     
-%7D%0A%0A
     
-private static void print(Node head) %7B%0A        for (Node n = head; n != null; n = n.next) %7B%0A            System.out.print(n.val + ' ');%0A        %7D%0A        System.out.println();%0A
+   tmp.prev = cn;%0A                %7D%0A        
     %7D%0A
-%0A
     
-public static void main(String%5B%5D args) %7B%0A        Problem430 prob = new Problem430()
+    %7D%0A        return head
 ;%0A  

Solve problem 430