#341

Flatten Nested List Iterator

specialist · 660 · lc medium +30 · 65.6% accepted · 5,068 likes · top 70%

play →

Description

You are given a nested list of integers nestedList where each element is either an integer or a further-nested list. Construct a flattening iterator that yields integers in the natural left-to-right traversal order.

Implement the NestedIterator class:

- NestedIterator(List<NestedInteger> nestedList) Sets up the iterator over nestedList.

- int next() Advances past and returns the next integer.

- boolean hasNext() Returns true when at least one integer remains.

Validation pseudocode:

initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res

Your iterator passes if res matches the fully flattened list.

Example 1:

initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return res

Example 2:

Input: nestedList = [[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].

Example 3:

Input: nestedList = [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].

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35