/
FlattenMultilevelDoublyLinkedList.java
51 lines (43 loc) · 1.18 KB
/
FlattenMultilevelDoublyLinkedList.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
50
51
/*
// Definition for a Node.
class Node {
public int val;
public Node prev;
public Node next;
public Node child;
};
*/
// https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
class Solution {
public Node flatten(Node head) {
// System.out.println(accumulate(head));
return build(accumulate(head));
}
List<Integer> accumulate(Node head) {
List<Integer> res = new ArrayList<>();
while (head != null) {
res.add(head.val);
if (head.child != null) {
res.addAll(accumulate(head.child));
}
head = head.next;
}
return res;
}
Node build(List<Integer> data) {
Node head = null, prev = null, res = null;
for (int x: data) {
if (head == null) {
head = new Node();
res = head;
}
head.val = x;
head.next = new Node();
head.prev = prev;
prev = head;
head = head.next;
}
if (prev != null) prev.next = null;
return res;
}
}