-
Notifications
You must be signed in to change notification settings - Fork 5
/
Day-10 Flatten a Multilevel Doubly Linked List
71 lines (62 loc) · 1.57 KB
/
Day-10 Flatten a Multilevel Doubly Linked List
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
// Definition for a Node.
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;
}
};
*/
class Solution {
public Node flatten(Node head) {
if(head==null) return head;
Node temp=head;
while(temp!=null){
if(temp.child!=null){
Node next=temp.next;
Node child=flatten(temp.child);
temp.child=null;
temp.next=child;
child.prev=temp;
while(child.next!=null){
child=child.next;
}
child.next=next;
if(next!=null)
next.prev=child;
temp=child;
}
temp=temp.next;
}
return head;
}
}
class Solution {
public Node flatten(Node head) {
if (head == null) return head;
Node pseudoHead = new Node(0, null, head, null);
Node curr, prev = pseudoHead;
Deque<Node> stack = new ArrayDeque<>();
stack.push(head);
while (!stack.isEmpty()) {
curr = stack.pop();
prev.next = curr;
curr.prev = prev;
if (curr.next != null) stack.push(curr.next);
if (curr.child != null) {
stack.push(curr.child);
curr.child = null;
}
prev = curr;
}
pseudoHead.next.prev = null;
return pseudoHead.next;
}
}