6ms stack of iterator


  • 0
    I
    public class NestedIterator implements Iterator<Integer> {
        private final Stack<Iterator<NestedInteger>> stack;
        private Integer next;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            stack = new Stack<>();
            stack.push(nestedList.iterator());
        }
    
        @Override
        public Integer next() {
            try{
                return next;
            }finally{
                next = null;
            }
        }
        
        @Override
        public boolean hasNext() {
            if(next != null) return true;
            
            next = nextInternal();
    
            return next != null;
        }
        
        private Integer nextInternal() {
            if(stack.empty()) return null;
            
            final Iterator<NestedInteger> iter = stack.peek();
    
            if(!iter.hasNext()) {
                stack.pop();
                return nextInternal();
            }
            
            final NestedInteger ni = iter.next();
    
            if(ni.isInteger()) {
                return ni.getInteger();
            }else {
                stack.push(ni.getList().iterator());
                return nextInternal();
            }
        }
    }```

Log in to reply
 

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