[Java] clean solution using stack


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

Log in to reply
 

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