Java solution using a stack


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

Log in to reply
 

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