Java Solution Using Stack


  • 0
    public class NestedIterator implements Iterator<Integer> {
        
        Deque<NestedInteger> stack;
        public NestedIterator(List<NestedInteger> nestedList) {
             stack = new LinkedList<NestedInteger>();
             for(int i = nestedList.size() - 1; i >= 0; i--) {
                 stack.offerFirst(nestedList.get(i));
             }
        }
    
        @Override
        public Integer next() {
            return stack.pollFirst().getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while(!stack.isEmpty() && !stack.peekFirst().isInteger()) {
                List<NestedInteger> list = stack.pollFirst().getList();
                for(int i = list.size() - 1; i >= 0; i--) {
                 stack.offerFirst(list.get(i));
                }
            }
            return stack.size() != 0;
        }
    }

Log in to reply
 

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