My 9ms JAVA solution using stack


  • 0
    M
    public class NestedIterator implements Iterator<Integer> {
        
        private Deque<NestedInteger> deque;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            deque = new ArrayDeque<NestedInteger>();
            for (int i=nestedList.size()-1; i>=0; i--) {
                deque.push(nestedList.get(i));
            }
        }
    
        @Override
        public Integer next() {
            hasNext();
            return deque.pop().getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while (!deque.isEmpty() && !deque.peek().isInteger()) {
                List<NestedInteger> top = deque.pop().getList();
                for (int i=top.size()-1; i>=0; i--) {
                    deque.push(top.get(i));
                }
            }
            return !deque.isEmpty();
        }
    }

Log in to reply
 

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