Flatten Nested List Iterator(Medium)
interface NestedInteger {
boolean isInteger();
Integer getInteger();
List<NestedInteger> getList();
}
public class NestedIterator implements Iterator<Integer> {
public NestedIterator(List<NestedInteger> nestedList) {
it = nestedList.iterator();
}
@Override
public Integer next() {
if (!components.isEmpty()) {
return components.pop();
} else {
throw new NoSuchElementException();
}
}
@Override
public boolean hasNext() {
while (components.isEmpty() && it.hasNext()) {
Stack<NestedInteger> stack = new Stack<NestedInteger>();
stack.push(it.next());
while (!stack.isEmpty()) {
NestedInteger cur = stack.pop();
if (cur.isInteger()) {
components.push(cur.getInteger());
} else if (cur.getList() != null) {
for (NestedInteger ni : cur.getList()) {
stack.push(ni);
}
}
}
}
return !components.isEmpty();
}
private Iterator<NestedInteger> it;
private Stack<Integer> components = new Stack<Integer>();
}