-
Notifications
You must be signed in to change notification settings - Fork 16
/
FlattenAMultiLevelDoublyLinkedList.java
49 lines (46 loc) · 1.58 KB
/
FlattenAMultiLevelDoublyLinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// T: O(n)
// S: O(n)
public class FlattenAMultiLevelDoublyLinkedList {
private static final class Node {
public int val;
public Node prev;
public Node next;
public Node child;
}
public Node flatten(Node head) {
for (Node temp = head ; temp != null ; temp = temp.next) {
if (temp.child != null) {
Node lastNodeOfFlattenedChildren = flattenLinkedList(temp.child);
lastNodeOfFlattenedChildren.next = temp.next;
if (temp.next != null) {
temp.next.prev = lastNodeOfFlattenedChildren;
}
temp.next = temp.child;
temp.child.prev = temp;
temp.child = null;
}
}
return head;
}
private Node flattenLinkedList(Node head) {
Node temp = head;
for (; temp.next != null ; temp = temp.next) {
if (temp.child != null) {
Node lastNodeOfFlattenedChildren = flattenLinkedList(temp.child);
lastNodeOfFlattenedChildren.next = temp.next;
temp.next.prev = lastNodeOfFlattenedChildren;
temp.next = temp.child;
temp.child.prev = temp;
temp.child = null;
}
}
if (temp.child != null) {
Node lastNodeOfFlattenedChildren = flattenLinkedList(temp.child);
temp.next = temp.child;
temp.child.prev = temp;
temp.child = null;
return lastNodeOfFlattenedChildren;
}
return temp;
}
}