#return true if there is another element in the whole structure
#int next()
#return the value of the next element in the structure
#void remove()
#remove (from the underlying collection) the last element returned by the iterator.
#That is, remove the element that the previous next() returned
#This method can be called only once per call to next(),
#otherwise an exception will be thrown.
#input: [[],[1,3],[5],[],[],[],[7],[],[9],[],[]]
input = [[], [1,2,3],[4,5],[],[],[],[7],[8],[9],[10],[]]
it = Iterator(input)
while it.hasNext():
val = it.next()
print(val)
if val % 2 == 0:
it.remove()
print(input)
我的代码如下
class Iterator:
def __init__(self, input):
self.input = input
self.outer_index = 0
self.inner_index = -1
def hasNext(self):
self.inner_index += 1
while self.outer_index < len(self.input):
element = self.input[self.outer_index]
#empty array
if len(element) == 0 or len(element) == self.inner_index:
self.inner_index = 0
self.outer_index += 1
else:
return True
return False
def next(self):
return self.input[self.outer_index][self.inner_index]
def remove(self):
temp_val = self.input[self.outer_index]
self.input[self.outer_index].pop(self.inner_index)
if len(temp_val) == 0:
self.outer_index += 1
else:
self.inner_index -= 1