LeetCode: 284. 顶端迭代器¶

1、题目描述¶

假设迭代器被初始化为列表 [1,2,3]。



**进阶：**你将如何拓展你的设计？使之变得通用化，从而适应所有的类型，而不只是整数型？

2、解题思路¶

​ 使用一个变量保存下一个值，依据这个值进行判断

# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
#     def __init__(self, nums):
#         """
#         Initializes an iterator object to the beginning of a list.
#         :type nums: List[int]
#         """
#
#     def hasNext(self):
#         """
#         Returns true if the iteration has more elements.
#         :rtype: bool
#         """
#
#     def next(self):
#         """
#         Returns the next element in the iteration.
#         :rtype: int
#         """

class PeekingIterator:
def __init__(self, iterator):
"""
:type iterator: Iterator
"""
self.iter = iterator
self.peek_value = self.iter.next() if self.iter.hasNext() else None

def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.peek_value

def next(self):
"""
:rtype: int
"""
temp = self.peek_value
self.peek_value = self.iter.next() if self.iter.hasNext() else None
return temp

def hasNext(self):
"""
:rtype: bool
"""
if self.peek_value != None:
return True
else:
return False

# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
#     val = iter.peek()   # Get the next element but not advance the iterator.
#     iter.next()         # Should return the same value as [val].