Simplest Java solution with stack and ListIterator


  • 0
    C

    The key idea is to use ListIterator which can go back (by calling previous()) in the list. This is needed because we want to properly handle case like [[]]. It's necessary to call next() in hasNext() to find out if the next element is an integer or a list.

    public class NestedIterator implements Iterator<Integer> {
        private final Deque<ListIterator<NestedInteger>> stack;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            stack = new ArrayDeque<>();
            stack.push(nestedList.listIterator());
        }
    
        @Override
        public Integer next() {
            if (!hasNext()) throw new NoSuchElementException("No more");
            return stack.peek().next().getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while(!stack.isEmpty()) {
                ListIterator<NestedInteger> it = stack.peek();
                if (!it.hasNext()) {
                    stack.pop();
                    continue;
                }
                NestedInteger nested = it.next();
                if (nested.isInteger()) {
                    it.previous();
                    return true;
                }
                stack.push(nested.getList().listIterator());
            }
            return false;
        }
    }
    

Log in to reply
 

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