Nested Integer类

Typical iterator should succeed as well in situation:

  1. next() call without hasNext() call

  2. multiple hasNext() calls

Flatten Nested List Iterator

  • Iterator的题首先要想到满足两个条件

    • next() call without hasNext() call

    • multiple hasNext() calls

  • push nestedList to a stack in reverse order, so that stack.peek() would be first NestedInteger

  • 一般都把logic写在hashNext()里

/*
push nestedList to a stack in reverse order, so that stakc.peek() would be first NestedInteger
*/
public class NestedIterator implements Iterator<Integer> {
    Stack<NestedInteger> stk;
    public NestedIterator(List<NestedInteger> nestedList) {
        stk = new Stack<>();
        prepare(nestedList);
    }

    @Override
    public Integer next() {
        return hasNext() == true ? stk.pop().getInteger() : null;
    }

    @Override
    public boolean hasNext() {
        while (!stk.isEmpty()) {
            if (stk.peek().isInteger()) return true;
            prepare(stk.pop().getList());
        }
        return false;
    }
    
    private void prepare(List<NestedInteger> list) {
        for (int i = list.size() - 1; i >=0 ;i--) {
            stk.push(list.get(i));
        }
    }
}

Nested list weight sum

Last updated

Was this helpful?