Short Java Solution with Stack and Recursion, 5ms, beats 97%

  • 0
    public class NestedIterator implements Iterator<Integer> {
        private Iterator<NestedInteger> current;
        private NestedInteger next;
        private Stack<Iterator<NestedInteger>> iterators;
        public NestedIterator(List<NestedInteger> nestedList) {
            current = nestedList.iterator();
            this.iterators = new Stack<>();
        public Integer next() {
            return next.getInteger();
        public boolean hasNext() {
            while(!current.hasNext()) {
                if (iterators.size() == 0) return false;
                current = iterators.pop();
            next =;
            if (next.isInteger()) return true;
            current = next.getList().iterator();
            return hasNext();

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.