forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_341.java
58 lines (48 loc) · 1.75 KB
/
_341.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
52
53
54
55
56
57
58
package com.fishercoder.solutions;
import com.fishercoder.common.classes.NestedInteger;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 341. Flatten Nested List Iterator
*
* Given a nested list of integers, implement an iterator to flatten it.
* Each element is either an integer, or a list -- whose elements may also be integers or other lists.
*
* Example 1:
* Given the list [[1,1],2,[1,1]],
* By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
*
* Example 2:
* Given the list [1,[4,[6]]],
* By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
*/
public class _341 {
public static class Solution1 {
public static class NestedIterator implements Iterator<Integer> {
private Queue<Integer> flattenedList;
public NestedIterator(List<NestedInteger> nestedList) {
flattenedList = new LinkedList<>();
constructList(nestedList);
}
private void constructList(List<NestedInteger> nestedList) {
for (NestedInteger nestedInteger : nestedList) {
if (nestedInteger.isInteger()) {
flattenedList.add(nestedInteger.getInteger());
} else {
constructList(nestedInteger.getList());
}
}
}
@Override
public Integer next() {
return flattenedList.poll();
}
@Override
public boolean hasNext() {
return !flattenedList.isEmpty();
}
}
}
}