classNestedIterator(object): def__init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.q = [(nestedList, 0)]
defnext(self): """ :rtype: int """
val = None not_find = True whileself.q and not_find: arr, num = self.q.pop() if num < len(arr): ele = arr[num] ifisinstance(ele, int): # 如果提交需要改成 ele.isInteger() val = ele # ................ ele.getInteger() not_find = False self.q.append((arr, num + 1)) else: self.q.append((arr, num + 1)) self.q.append((ele, 0)) # 如果提交改成,self.q.append((ele.getList(),0))
returnNoneif not_find else val
defhasNext(self): """ :rtype: bool """ has_next = False whilenot has_next andself.q: arr, num = self.q.pop() if num < len(arr): ele = arr[num] ifisinstance(ele, int): has_next = True self.q.append((arr, num)) else: self.q.append((arr, num + 1)) self.q.append((ele, 0))
return has_next
if __name__ == "__main__": nestedlist = [[1, 2], 3, [4, 5], 6] i, v = NestedIterator(nestedlist), [] while i.hasNext(): v.append(i.next()) print(v) # [1, 2, 3, 4, 5, 6]
val = None not_find = True whileself.q and not_find: arr, num = self.q.pop() if num < len(arr): ele = arr[num] ifisinstance(ele, int): val = ele not_find = False self.q.append((arr, num + 1)) else: self.q.append((arr, num + 1)) self.q.append((ele, 0))