Flatten Nested List Iterator
Given a nested list of integers, implement an iterator to flatten it.
Each element was either an integer, or a list--whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]]
,
By calling next repeatedly until hasnext returns FALSE, the order of elements returned by next should be: [1,1,2,1,1]
.
Example 2:
Given the list [1,[4,[6]]]
,
By calling next repeatedly until hasnext returns FALSE, the order of elements returned by next should be: [1,4,6]
.
Flatten nested list.
From the way it is called, it is always called to the last, so recursively expands all the numbers in the constructor into an array.
Another way is to push the nested list to the stack and take it from the stack when needed.
Note that you need to invoke the Isinteger (), Getinteger (), and GetList () three methods in the comments.
1 # """2 #This is the interface, allows for creating nested lists.3 #You should not implement it, or speculate on its implementation4 # """5 #class Nestedinteger (object):6 #def isinteger (self):7 # """8 #@return True If this nestedinteger holds a single integer, rather than a nested list.9 #: rtype boolTen # """ One # A #def getinteger (self): - # """ - #@return The single integer which this nestedinteger holds, if it holds a single integer the #Return None If this nestedinteger holds a nested list - #: Rtype int - # """ - # + #def getList (self): - # """ + #@return The nested list that this nestedinteger holds, if it holds a nested list A #Return None If this nestedinteger holds a single integer at #: Rtype List[nestedinteger] - # """ - classNestediterator (object): - - def __init__(self, nestedlist): - """ in Initialize your data structure here. - : Type Nestedlist:list[nestedinteger] to """ +Self.__list= [] -Self.__index=0 theSelf.__getlist(nestedlist) * $ def __getlist(self, nestedlist):Panax Notoginseng forIteminchnestedlist: - ifItem.isinteger (): theSelf.__list. Append (Item.getinteger ()) + Else: ASelf.__getlist(Item.getlist ()) the + defNext (self): - """ $ : Rtype:int $ """ -res = self.__list[Self.__index] -Self.__index+ = 1 the returnRes - Wuyi defHasnext (self): the """ - : Rtype:bool Wu """ - if(self.)__index< Len (self.__list)): About returnTrue $ returnFalse
[Leetcode] [Python] Flatten Nested List Iterator