Leetcode 341 Solution

This article provides solution to leetcode question 341 (flatten-nested-list-iterator)

https://leetcode.com/problems/flatten-nested-list-iterator

Solution

# """
# 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.s = [(nestedList, 0)]

    def next(self) -> int:
        self.hasNext()

        return self.s.pop()[0]

    def hasNext(self) -> bool:
        if not self.s:
            return False

        while self.s:
            ele = self.s.pop()

            if isinstance(ele[0], int):
                self.s.append((ele[0], int))
                return True
            elif isinstance(ele[0], list):
                lst, index = ele

                if index == len(lst):
                    continue

                if index < len(lst):
                    self.s.append((lst, index + 1))

                if lst[index].isInteger():
                    self.s.append((lst[index].getInteger(), 0))
                else:
                    self.s.append((lst[index].getList(), 0))
            else:
                raise Exception("Unexpected type '{}'!".format(type(ele[0])))

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