Peeking Iterator
Question Description
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.
Solution
Here we just use an extra variable top in the class to notify if the peek() operation has been called. If so, we assign value to top for the use of next() or peek() operation.
And if we call the next() operation, if the top variable exists, we return it and set the top to None; if not, we just use the next() of class Iterator.
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.top = None
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.top:
self.top = self.iterator.next()
return self.top
def next(self):
"""
:rtype: int
"""
if self.top:
result = self.top
self.top = None
return result
else:
return self.iterator.next()
def hasNext(self):
"""
:rtype: bool
"""
return bool(self.top) or self.iterator.hasNext()