Skip to content

Commit f835976

Browse files
committed
Update 341_Flatten_Nested_List_Iterator.java
1 parent f4fdeff commit f835976

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed
Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,43 @@
11
public class NestedIterator implements Iterator<Integer> {
2-
private Queue<NestedInteger> q;
2+
private Deque<Iterator<NestedInteger>> st;
3+
private Integer next;
34

45
public NestedIterator(List<NestedInteger> nestedList) {
5-
q = new LinkedList<>();
6-
flatten(nestedList);
6+
st = new ArrayDeque<>();
7+
st.push(nestedList.iterator());
8+
advance();
79
}
810

9-
private void flatten(List<NestedInteger> nestedList) {
10-
if (nestedList == null) {
11-
return;
12-
}
11+
private void advance() {
12+
next = null;
13+
14+
while (!st.isEmpty()) {
15+
Iterator<NestedInteger> it = st.peekFirst();
1316

14-
for (NestedInteger n : nestedList) {
15-
if (n.isInteger()) {
16-
q.offer(n);
17+
if (!it.hasNext()) {
18+
st.pollFirst();
1719
} else {
18-
flatten(n.getList());
20+
NestedInteger n = it.next();
21+
22+
if (n.isInteger()) {
23+
next = n.getInteger();
24+
return;
25+
} else {
26+
st.push(n.getList().iterator());
27+
}
1928
}
2029
}
2130
}
2231

2332
@Override
2433
public Integer next() {
25-
return hasNext() ? q.poll().getInteger() : null;
34+
Integer n = next;
35+
advance();
36+
return n;
2637
}
2738

2839
@Override
2940
public boolean hasNext() {
30-
return !q.isEmpty();
41+
return next != null;
3142
}
3243
}

0 commit comments

Comments
 (0)