22. Flatten List
中文English
Given a list, each element in the list can be a list or integer. flatten it into a simply list with integers.
Example
Example 1:
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation:
flatten it into a simply list with integers.
Example 2:
Input: [1,2,[1,2]]
Output:[1,2,1,2]
Explanation:
flatten it into a simply list with integers.
Example 3:
Input: [4,[3,[2,[1]]]]
Output:[4,3,2,1]
Explanation:
flatten it into a simply list with integers.
Challenge
Do it in non-recursive.
Notice
If the element in the given list is a list, it can contain list too.
classSolution(ob
ject):# @param nestedList a list, each element in the list # can be a list or integer, for example [1,2,[1,2]]# @return {int[]} a list of integerdefflatten(self, nestedList):# Write your code hereiftype(nestedList)==int:return[nestedList]
s =[]
result =[]
it =iter(nestedList)whileTrue:try:
t =next(it)iftype(t)==int:
result.append(t)else:
s.append(it)
it =iter(t)except StopIteration:iflen(s)==0:break
it = s.pop()return result