Flatten Nested List Iterator

Problem: Flatten Nested List Iterator

We can store the reversed nested list. Everytime we ask about the first element, we check the last element of our stored ones. If that element is an list, we will extend it to current stored list and do that checking recursively until we get an integer.

Code in Python:

# """
# 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]
#        """
from collections import deque

class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.nl = nestedList[::-1]

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

    def hasNext(self):
        """
        :rtype: bool
        """
        while self.nl and not self.nl[-1].isInteger():
            self.nl.extend(self.nl.pop().getList()[::-1])
        return bool(self.nl)


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

results matching ""

    No results matching ""