Java Solution, Stack of Iterator, recursive, preset value


  • 1
    A
    public class NestedIterator implements Iterator<Integer> {
        
        private Stack<Iterator<NestedInteger>> iters;
        private int nextInt;
        private boolean hasNextInt;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            iters = new Stack<Iterator<NestedInteger>>();
            iters.push(nestedList.iterator());
            hasNextInt = retrieveNext();
        }
    
        @Override
        public Integer next() {
            // if (!hasNextInt) {
            //     throw new NoSuchElementException();
            // }
            
            int ret = nextInt;
            hasNextInt = retrieveNext();
            return ret;
        }
    
        @Override
        public boolean hasNext() {
            return hasNextInt;
        }
        
        private boolean retrieveNext() {
            if (iters.empty()) {
                // reach the end
                return false;
            }
            else {
                Iterator<NestedInteger> top = iters.peek();
                if (!top.hasNext()) {
                    // no more elements in the top list
                    iters.pop();
                    return retrieveNext();
                }
                else {
                    NestedInteger nt = top.next();
                    if (nt.isInteger()) {
                        // an integer
                        nextInt = nt.getInteger();
                        return true;
                    }
                    else {
                        // a list
                        iters.push((nt.getList()).iterator());
                        return retrieveNext();
                    }
                }
            }
        }
    }

Log in to reply
 

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