A question before this is the Nested List Weight Sum, and it requires recursion to solve. As it carries to this problem that we will need recursion to solve it. But since we need to access each NestedInteger at a time, we will use a stack to help.

In the constructor, we push all the nestedList into the stack from back to front, so when we pop the stack, it returns the very first element. Second, in the hasNext() function, we peek the first element in stack currently, and if it is an Integer, we will return true and pop the element. If it is a list, we will further flatten it. This is iterative version of flatting the nested list. Again, we need to iterate from the back to front of the list.

X. Better Using a stack of ListIterators.https://discuss.leetcode.com/topic/44983/share-my-java-neat-solution-8mswhat I do is just tokeep an additional field storing the next integerIf we call hasNext() multiple times before calling next() it will not give the right result since you are calling next on Iterator<NestedInteger> in hasNext() method which means that every time you call hasNext() it will remove the next Integer from the list.

In my opinion an iterator shouldn't copy the entire data (which some solutions have done) but just iterate over the original data structure.

I keep the current progress in a stack. My hasNext tries to find an integer. My next returns it and moves on. I call hasNext in nextbecause hasNext is optional. Some user of the iterator might call only next and never hasNext, e.g., if they know how many integers are in the structure or if they want to handle the ending with exception handling.