问题描述:
Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be returned by the next call to next().
Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].
Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.
You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.
算法:
将关注点着眼于数据,直接对数据(iterator, top, isPeeked)操作。
通过引入顶端元素top,和判断数据isPeeked对迭代器的状态进行判断。
当迭代未开始时:top=None, isPeeked = False
当迭代终止时:top=None, isPeeked = False
中间状态为:top is not None, isPeeked = True
在函数中,要判断状态并进行转换。
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
# 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(object):
def __init__(self, iterator):
""" Initialize your data structure here. :type iterator: Iterator """
self.iterator = iterator
self.top = None # for next
self.isPeeked = False # is peeked?
def peek(self):
""" Returns the next element in the iteration without advancing the iterator. :rtype: int """
if self.isPeeked:
return self.top
else:
if self.iterator.hasNext():
self.top = self.iterator.next()
self.isPeeked = True
return self.top
else:
self.top = None
self.isPeeked = False
return self.top
def next(self):
""" :rtype: int """
if self.isPeeked:
if self.iterator.hasNext():
value = self.top
self.top = self.iterator.next()
return value
else:
value = self.top
self.top = None
self.isPeeked = False
return value
else:
if self.iterator.hasNext():
value = self.iterator.next()
self.top = self.iterator.next()
self.isPeeked = True
return value
else:
self.top = None
self.isPeeked = False
return None
def hasNext(self):
""" :rtype: bool """
if self.iterator.hasNext():
return True
else:
return self.top is not None
# 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].