# 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

*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://syjohnson11.gitbook.io/leetcode/shixian_iterator/nested-integer-lei.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
