1. 程式人生 > 實用技巧 >leetcode_341. 扁平化巢狀列表迭代器

leetcode_341. 扁平化巢狀列表迭代器

給你一個巢狀的整型列表。請你設計一個迭代器,使其能夠遍歷這個整型列表中的所有整數。

列表中的每一項或者為一個整數,或者是另一個列表。其中列表的元素也可能是整數或是其他列表。



示例 1:

輸入: [[1,1],2,[1,1]]
輸出: [1,1,2,1,1]
解釋: 通過重複呼叫next 直到hasNext 返回 false,next返回的元素的順序應該是: [1,1,2,1,1]。
示例 2:

輸入: [1,[4,[6]]]
輸出: [1,4,6]
解釋: 通過重複呼叫next直到hasNext 返回 false,next返回的元素的順序應該是: [1,4,6]。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/flatten-nested-list-iterator
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
#    def isInteger(self) -> bool:
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        """
#
#    def getInteger(self) -> int:
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        """
#
#    def getList(self) -> [NestedInteger]:
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        """

class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        self.ls=[]
        def getls(nestedList:[NestedInteger]):
           for x in nestedList:
                if x.isInteger():
                   self.ls.append(x.getInteger())
                else:
                    getls(x.getList())

        getls(nestedList)

        
    
    def next(self) -> int:
        return self.ls.pop(0)
        
    
    def hasNext(self) -> bool:
        return len(self.ls)
        
         

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())