Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active October 17, 2017 22:07
Show Gist options
  • Save cixuuz/86642bb516c9e650f973d9c25481d3bc to your computer and use it in GitHub Desktop.
Save cixuuz/86642bb516c9e650f973d9c25481d3bc to your computer and use it in GitHub Desktop.
[341. Flatten Nested List Iterator] #leetcode
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