341. Flatten Nested List Iterator

341. Flatten Nested List Iteratorarrow-up-right

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 list nestedList.

  • int next() Returns the next integer in the nested list.

  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

Example 1:

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 2:

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].

Constraints:

  • 1 <= nestedList.length <= 500

  • The values of the integers in the nested list is in the range [-106, 106].

My Solutions:

方法1:因为要保持element的order,在constructor里从后往前遍历元素,加到stack里面,这样保证排在后面的element最后出。在hasNext里处理元素,如果最上面的元素不是integer,把他们从后往前加入到stack里。

方法2:写一个function先把所有元素都先加进一个list,用来存贮integer。用一个int指针代表已经next出到第几个元素。

Last updated