Flatten a multilevel doubly Linked List - Java recursion
Can someone explain to me why I'm getting:
The linked list [1,2,3,7,8,11,12,9,10,4,5,6] is not a valid doubly linked list.
class Solution {
Node flattenedList = new Node(-1);
Node flattenedListPointer = flattenedList;
public Node flatten(Node head) {
if (head == null){
return flattenedList.next;
}
flattenedListPointer.next = new Node(head.val,head.prev,null,null);
flattenedListPointer = flattenedListPointer.next;
if (head.child != null){
flatten(head.child);
}
if (head.next != null){
flatten(head.next);
}
return flattenedList.next;
}
}
[1,2,3,7,8,11,12,9,10,4,5,6] is the expected answer - and I did make all the child nodes to be null (as require).
I also made sure all the prev node are null.
Thanks!