Skip to content

Instantly share code, notes, and snippets.

@yokolet
Last active June 16, 2017 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/e9f1387f213e872d15697d5d13eaedcd to your computer and use it in GitHub Desktop.
Save yokolet/e9f1387f213e872d15697d5d13eaedcd to your computer and use it in GitHub Desktop.
import java.util.*;
public class NestedListIterator implements Iterator<Integer> {
interface NestedInteger {
boolean isInteger();
Integer getInteger();
List<NestedInteger> getList();
}
Stack<Iterator<NestedInteger>> stack;
Integer current = null;
void updateIterator() {
while (!stack.isEmpty() && current == null) {
Iterator<NestedInteger> top = stack.peek();
if (!top.hasNext()) {
stack.pop();
continue;
}
NestedInteger ni = top.next();
if (ni.isInteger()) {
current = ni.getInteger();
} else {
stack.push(ni.getList().iterator());
}
}
}
NestedListIterator(List<NestedInteger> nestedList) {
stack = new Stack();
stack.push(nestedList.iterator());
updateIterator();
}
@Override
public boolean hasNext() {
return current != null ? true : false;
}
@Override
public Integer next() {
Integer temp = current;
current = null;
updateIterator();
return temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment