# 341. Flatten Nested List Iterator
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.
Example 1:
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].
Example 2:
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].
# Solution
Approach 1: recursion.
# Code (Python)
Approach 1:
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
def generate(nested):
for item in nested:
if item.isInteger():
yield item.getInteger()
else:
for element in generate(item.getList()):
yield element
self.next_item = None
self.generator = generate(nestedList)
def next(self) -> int:
if self.next_item != None:
tmp = self.next_item
self.next_item = None
return tmp
return next(self.generator)
def hasNext(self) -> bool:
if self.next_item != None:
return True
try:
self.next_item = next(self.generator)
except StopIteration as e:
return False
return True
# Code (C++)
Approach 1:
Approach 2: