341. Flatten Nested List Iterator
Question
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:
initialize iterator with nestedList
res = []
while iterator.hasNext()
append iterator.next() to the end of res
return resIf
res
matches the expected flattened list, then your code will be judged as correct.
Solution
将所有的NestedInteger展开后加入全局变量队列。
辅助方法buildQueue():
递归,如果当前元素是列表,则向下递归列表内的所有元素。
如果当前元素是单个整数,则将其加入队列。
next():
返回并挤出队列中的下一个元素,返回其整数。
hasNext():
返回队列是否为空。
Code
1 | /** |