341. Flatten Nested List Iterato

2016-09-21  本文已影响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())
上一篇 下一篇

猜你喜欢

热点阅读