my solution using generator


  • 0
    U
    def nested_list_generator(nestedList):
        for ele in nestedList:
            if ele.isInteger():
                yield ele
            else:
                gen = nested_list_generator(ele.getList())
                for e in gen:
                    yield e
        
    
    class NestedIterator(object):
    
        def __init__(self, nestedList):
            # Initialize your data structure here.
            self.lst = nestedList
            self.__next = None
            self.__gen = nested_list_generator(nestedList)
            
        # @return {int} the next element in the iteration
        def next(self):
            # Write your code here
            if self.__next:
                next = self.__next
                self.__next = None
                return next.getInteger()
            else:
                try:
                    next = self.__gen.next()
                except StopIteration:
                    next = None
                return next.getInteger()
            
        # @return {boolean} true if the iteration has more element or false
        def hasNext(self):
            # Write your code here
            if self.__next:
                return True
            else:
                try:
                    next = self.__gen.next()
                except StopIteration:
                    return False
                else:
                    self.__next = next
                    return True
            
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.