341. Flatten Nested List Iterator

文章目录
  1. 1. 题目
  2. 2. 思路

题目

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

思路

看到题我的第一反应是用栈来解决,一个个进行pop就行,所以代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class NestedIterator(object):

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

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

def hasNext(self):
"""
:rtype: bool
"""
while self.list or self.stack:
if not self.stack:
self.stack.append(self.list.pop(0))
while self.stack and not self.stack[-1].isInteger():
top = self.stack.pop().getList()
for e in top[::-1]:
self.stack.append(e)
if self.stack and self.stack[-1].isInteger():
return True
return False