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


  • 0
    S
    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<>();
            iterators.push(current);
        }
    
        @Override
        public Integer next() {
            return next.getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while(!current.hasNext()) {
                if (iterators.size() == 0) return false;
                current = iterators.pop();
            }
            next = current.next();
            if (next.isInteger()) return true;
    
            iterators.push(current);
            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.