Java Solution using List's Iterator with Stack


  • 0
    public class NestedIterator implements Iterator<Integer> {
        
        Stack<Iterator<NestedInteger>> stk;
        Integer nextVal;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            Iterator<NestedInteger> itr = nestedList.iterator();
            stk = new Stack<>();
            nextVal = null;
            if(itr.hasNext()) {
                stk.push(itr);
                advance();
            }
        }
        
        private void advance() {
            nextVal = null;
            while(!stk.empty() && !stk.peek().hasNext())
                stk.pop();
            if(!stk.empty()) {
                NestedInteger n = stk.peek().next();
                while(!n.isInteger()) {
                    Iterator<NestedInteger> subItr = n.getList().iterator();
                    if(subItr.hasNext()) {
                        stk.push(subItr);
                        n = subItr.next();
                    } else {
                        while(!stk.empty() && !stk.peek().hasNext())
                            stk.pop();
                        if(stk.empty())
                            return;
                        else
                            n = stk.peek().next();
                    }
                }
                nextVal = n.getInteger();
            }
        }
    
        @Override
        public Integer next() {
            Integer res = nextVal;
            advance();
            return res;
        }
    
        @Override
        public boolean hasNext() {
            return nextVal!=null;
        }
    }

Log in to reply
 

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