美文网首页
341. Flatten Nested List Iterato

341. Flatten Nested List Iterato

作者: 阿团相信梦想都能实现 | 来源:发表于2016-09-21 07:05 被阅读0次
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
#    def isInteger(self):
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        :rtype bool
#        """
#
#    def getInteger(self):
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        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
#        Return None if this NestedInteger holds a single integer
#        :rtype List[NestedInteger]
#        """
import collections 

class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.stack=[]
        for item in reversed(nestedList):
            self.stack.append(item)
       

    def next(self):
        """
        :rtype: int
        """
        return self.stack.pop().getInteger()

    def hasNext(self):
        """
        :rtype: bool
        """
        while (self.stack):#while there is still elements left to read 
            #if the last element in the stack is integer , then simply return True
            if self.stack[-1].isInteger():return True 
            #if the last element is a list, then pop it and add its elements into the stack
            
            t=self.stack.pop().getList()
            
            for item in reversed(t):
                self.stack.append(item)
        return False
        

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

相关文章

网友评论

      本文标题:341. Flatten Nested List Iterato

      本文链接:https://www.haomeiwen.com/subject/mdtaettx.html