Flatten a Multilevel Doubly Linked List LeetCode solution in Java

1
class Solution {
2
public Node flatten(Node head) {
3
Node curr = head; // for traversal
4
Node tail = head; // for keeping the track of previous node
5
Stack<Node> stack =
6
new Stack<>(); // for storing the reference of next node when child node encounters
7
while (curr != null) {
8
if (curr.child != null) { // if there is a child
9
Node child = curr.child; // creating a node for child
10
if (curr.next != null) { // if there is list after we find child a child
11
stack.push(curr.next); // pushing the list to the stack
12
curr.next.prev = null; // pointing its previous to null
13
}
14
curr.next = child; // pointing the current's reference to child
15
child.prev = curr; // pointing child's previous reference to current.
16
curr.child = null; // pointing the current's child pointer to null
17
}
18
tail = curr; // for keeping track of previous nodes
19
curr = curr.next; // traversing
20
}
21
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 stack
23
tail.next = curr; // pointing the previos node to the last node
24
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
26
tail = curr;
27
curr = curr.next;
28
}
29
}
30
return head;
31
}
32
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0