/*
* Below is the interface for Iterator, which is already defined for you.
* **DO NOT** modify the interface for Iterator.
*
* class Iterator {
* struct Data;
* Data* data;
* public:
* Iterator(const vector<int>& nums);
* Iterator(const Iterator& iter);
*
* // Returns the next element in the iteration.
* int next();
*
* // Returns true if the iteration has more elements.
* bool hasNext() const;
* };
*/
class PeekingIterator : public Iterator {
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
// Initialize any member here.
// **DO NOT** save a copy of nums and manipulate it directly.
// You should only use the Iterator interface methods.
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
}
bool hasNext() const {
}
};
/* Below is the interface for Iterator, which is already defined for you.
*
* type Iterator struct {
*
* }
*
* func (this *Iterator) hasNext() bool {
* // Returns true if the iteration has more elements.
* }
*
* func (this *Iterator) next() int {
* // Returns the next element in the iteration.
* }
*/
type PeekingIterator struct {
iter *Iterator
_hasNext bool
_next int
}
func Constructor(iter *Iterator) *PeekingIterator {
return &PeekingIterator{iter, iter.hasNext(), iter.next()}
}
func (it *PeekingIterator) hasNext() bool {
return it._hasNext
}
func (it *PeekingIterator) next() int {
ret := it._next
it._hasNext = it.iter.hasNext()
if it._hasNext {
it._next = it.iter.next()
}
return ret
}
func (it *PeekingIterator) peek() int {
return it._next
}
# 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):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self._next = iterator.next()
self._hasNext = iterator.hasNext()
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self._next
def next(self):
"""
:rtype: int
"""
ret = self._next
self._hasNext = self.iterator.hasNext()
self._next = self.iterator.next() if self._hasNext else 0
return ret
def hasNext(self):
"""
:rtype: bool
"""
return self._hasNext
# 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].