341. Flatten Nested List Iterator
341. Flatten Nested List Iterator
Description
Difficulty: Medium
Related Topics: Stack, Tree, Depth-First Search, Design, Queue, Iterator
You are given a nested list of integers nestedList
. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator
class:
NestedIterator(List<NestedInteger> nestedList)
Initializes the iterator with the nested listnestedList
.int next()
Returns the next integer in the nested list.boolean hasNext()
Returnstrue
if there are still some integers in the nested list andfalse
otherwise.
Your code will be tested with the following pseudocode:
1 | initialize iterator with nestedList |
If res
matches the expected flattened list, then your code will be judged as correct.
Example 1:
1 | Input: nestedList = [[1,1],2,[1,1]] |
Example 2:
1 | Input: nestedList = [1,[4,[6]]] |
Constraints:
1 <= nestedList.length <= 500
- The values of the integers in the nested list is in the range [-106, 106].
Hints/Notes
- we can do the traverse and generate the list during construction, or we can do the lazy iterator, which only check if there’s next item when calling
hasNext()
- lazy iterator is better, and it needs us to change the vector when calling
hasNext()
- deque provides the best performance, since we don’t care about random access and deque
allocates memory in large blocks
Solution
Language: C++
1 | /** |