Created
October 2, 2018 18:31
-
-
Save yokolet/82505cef83b466647813182ce6f9a07d to your computer and use it in GitHub Desktop.
Flatten Nested List Iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Description: | |
| Given a nested list of integers, implement an iterator to flatten it. Each element is | |
| either an integer, or a list -- whose elements may also be integers or other lists. | |
| Use API below to implement the class: | |
| """ | |
| #class NestedInteger: | |
| # 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] | |
| # """ | |
| """ | |
| Examples: | |
| Input: [[1,1],2,[1,1]] | |
| Output: [1,1,2,1,1] | |
| Input: [1,[4,[6]]] | |
| Output: [1,4,6] | |
| """ | |
| class NestedIterator: | |
| def __init__(self, nestedList): | |
| """ | |
| Initialize your data structure here. | |
| :type nestedList: List[NestedInteger] | |
| """ | |
| self.stack = [iter(nestedList)] | |
| self.cur = None | |
| self.__update__() | |
| def __update__(self): | |
| while self.stack and self.cur == None: | |
| curIter = self.stack[-1] | |
| try: | |
| nested = next(curIter) | |
| if nested.isInteger(): | |
| self.cur = nested.getInteger() | |
| else: | |
| self.stack.append(iter(nested.getList())) | |
| except StopIteration: | |
| self.stack.pop() | |
| continue | |
| def next(self): | |
| """ | |
| :rtype: int | |
| """ | |
| value = self.cur | |
| self.cur = None | |
| self.__update__() | |
| return value | |
| def hasNext(self): | |
| """ | |
| :rtype: bool | |
| """ | |
| return self.cur != None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment