Simplest Java solution with stack and ListIterator

  • 0

    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<>();
        public Integer next() {
            if (!hasNext()) throw new NoSuchElementException("No more");
            return stack.peek().next().getInteger();
        public boolean hasNext() {
            while(!stack.isEmpty()) {
                ListIterator<NestedInteger> it = stack.peek();
                if (!it.hasNext()) {
                NestedInteger nested =;
                if (nested.isInteger()) {
                    return true;
            return false;

Log in to reply

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