2
public Node flatten(Node head) {3
Node curr = head; // for traversal4
Node tail = head; // for keeping the track of previous node6
new Stack<>(); // for storing the reference of next node when child node encounters8
if (curr.child != null) { // if there is a child9
Node child = curr.child; // creating a node for child10
if (curr.next != null) { // if there is list after we find child a child11
stack.push(curr.next); // pushing the list to the stack12
curr.next.prev = null; // pointing its previous to null14
curr.next = child; // pointing the current's reference to child15
child.prev = curr; // pointing child's previous reference to current.16
curr.child = null; // pointing the current's child pointer to null18
tail = curr; // for keeping track of previous nodes19
curr = curr.next; // traversing21
while (!stack.isEmpty()) { // checking if the stack has still nodes in it.22
curr = stack.pop(); // getting the last node of the list pushed into the stack23
tail.next = curr; // pointing the previos node to the last node24
curr.prev = tail; // pointing previos pointer of the last node to the previos node.25
while (curr != null) { // traversing the last node's popped out of stack