Skip to content

Commit 1f5fdfc

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 341_Flatten_Nested_List_Iterator.java
1 parent cbd7c15 commit 1f5fdfc

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class NestedIterator implements Iterator<Integer> {
2+
private Queue<NestedInteger> q;
3+
4+
public NestedIterator(List<NestedInteger> nestedList) {
5+
q = new LinkedList<>();
6+
flatten(nestedList);
7+
}
8+
9+
private void flatten(List<NestedInteger> nestedList) {
10+
if (nestedList == null) {
11+
return;
12+
}
13+
14+
for (NestedInteger n : nestedList) {
15+
if (n.isInteger()) {
16+
q.offer(n);
17+
} else {
18+
flatten(n.getList());
19+
}
20+
}
21+
}
22+
23+
@Override
24+
public Integer next() {
25+
return hasNext() ? q.poll().getInteger() : null;
26+
}
27+
28+
@Override
29+
public boolean hasNext() {
30+
return !q.isEmpty();
31+
}
32+
}

0 commit comments

Comments
 (0)