7ms solution using stack<iterator>, can someone analyze pros and cons?


  • 0
    X
    public class NestedIterator implements Iterator<Integer> {
        private Iterator iter = null;
        private Stack<Iterator> iters = new Stack<Iterator>();
        private NestedInteger temp = null;
        public NestedIterator(List<NestedInteger> nestedList) {
            iter = nestedList.iterator();
            if (iter.hasNext()) {
                iters.push(iter);
            }
        }
    
        @Override
        public Integer next() {
           return temp.getInteger();
        }
    
        @Override
        public boolean hasNext() {
            if (iters.isEmpty()) {
                return false;
            }
            iter = iters.peek();
            temp = (NestedInteger)iter.next();
            if (!iter.hasNext()) {
                iters.pop();
            }
            if (temp.isInteger()) {
                return true;
            } else {
                Iterator tempIter = temp.getList().iterator();
                if (tempIter.hasNext()) {
                    iters.push(tempIter);
                }
                return this.hasNext();
            }
        }
    }

Log in to reply
 

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