Last active
October 17, 2017 22:07
-
-
Save cixuuz/86642bb516c9e650f973d9c25481d3bc to your computer and use it in GitHub Desktop.
[341. Flatten Nested List Iterator] #leetcode
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
class NestedIterator(object): | |
def __init__(self, nestedList): | |
""" | |
Initialize your data structure here. | |
:type nestedList: List[NestedInteger] | |
""" | |
def gen(nestedList): | |
for x in nestedList: | |
if x.isInteger(): | |
yield x.getInteger() | |
else: | |
for y in gen(x.getList()): | |
yield y | |
self.gen = gen(nestedList) | |
def next(self): | |
""" | |
:rtype: int | |
""" | |
return self.value | |
def hasNext(self): | |
""" | |
:rtype: bool | |
""" | |
try: | |
self.value = next(self.gen) | |
return True | |
except StopIteration: | |
return False | |
class NestedIterator(object): | |
def __init__(self, nestedList): | |
self.stack = [[nestedList, 0]] | |
def next(self): | |
self.hasNext() | |
nestedList, i = self.stack[-1] | |
self.stack[-1][1] += 1 | |
return nestedList[i].getInteger() | |
def hasNext(self): | |
s = self.stack | |
while s: | |
nestedList, i = s[-1] | |
if i == len(nestedList): | |
s.pop() | |
else: | |
x = nestedList[i] | |
if x.isInteger(): | |
return True | |
s[-1][1] += 1 | |
s.append([x.getList(), 0]) | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment