LintCode Q528 Flatten Nested List Iterator in Python

  • Jinhai ZHOU
  • 6 Minutes
  • 2016年11月2日
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return {boolean} True if this NestedInteger holds a single integer,
# rather than a nested list.
# """
#
# def getInteger(self):
# """
# @return {int} 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):
# """
# @return {NestedInteger[]} the nested list that this NestedInteger holds,
# if it holds a nested list
# Return None if this NestedInteger holds a single integer
# """
class NestedIterator(object):
def __init__(self, nestedList):
# Initialize your data structure here.
self._nestedList = nestedList
self._nestedList.reverse()
# @return {int} the next element in the iteration
def next(self):
# Write your code here
current = self._nestedList.pop()
return current.getInteger()
# @return {boolean} true if the iteration has more element or false
def hasNext(self):
# Write your code here
while self._nestedList:
if self._nestedList[-1].isInteger():
return True
listInteger = self._nestedList.pop().getList()
for i in xrange(len(listInteger)-1, -1, -1):
self._nestedList.append(listInteger[i])
return False
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。