-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNestedIterator.java
More file actions
53 lines (43 loc) · 1.38 KB
/
NestedIterator.java
File metadata and controls
53 lines (43 loc) · 1.38 KB
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
import java.util.*;
public class NestedIterator implements Iterator<Integer> {
List<NestedInteger> nestedList;
Deque<NestedInteger> stack;
Deque<Integer> queue;
public NestedIterator(List<NestedInteger> nestedList) {
this.nestedList = nestedList;
stack = new LinkedList<>();
queue = new LinkedList<>();
}
private void flattenList(){
stack.addFirst(nestedList.get(0));
while(!stack.isEmpty()){
NestedInteger n = stack.pop();
if(n.isInteger()){
int num = n.getInteger();
queue.add(num);
}else {
if (n.getList() != null)
for(NestedInteger l : n.getList()){
stack.addFirst(l);
}
}
}
}
@Override
public Integer next() {
flattenList();
if(hasNext()){
return queue.poll();
}
return -1;
}
@Override
public boolean hasNext() {
return !queue.isEmpty();
}
public static void main(String [] args){
List<NestedInteger> list = new ArrayList<>();
//NestedInteger n1 = new
// NestedIterator i = new NestedIterator(nestedList);
}
}