Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list – whose elements may also be integers or other lists.
Note:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Input: [[1,1],2,[1,1]] Output: [1,1,2,1,1] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
Input: [1,[4,[6]]] Output: [1,4,6] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
Use a stack to store all NestedInteger. At the beginning, we push into all NestedInteger. Every time we call hasNext(), we push into all NestedInteger if the current item is a list; otherwise (an integer), we stop and it is ready for calling next().
In other words, you can say that hasNext() always keep the top item of stack is an integer. It is obvious that hasNext() returns false if the stack is empty.