Peeking Iterator
Discussion
这道题让我们实现一个顶端迭代器,在普通的迭代器类Iterator的基础上增加了peek的功能,就是返回查看下一个值的功能,但是不移动指针,next()函数才会移动指针,那我们可以定义一个变量专门来保存下一个值,再用一个bool型变量标记是否保存了下一个值,再调用原来的一些成员函数,就可以实现这个顶端迭代器了.
Solution
// 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);
virtual ~Iterator();
// 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.
has_peeked = false;
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
if(has_peeked == false) {
has_peeked = true;
value = Iterator::next();
}
return value;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
//has_peeked is true means "value" has been updated in peek()
if(has_peeked == false) return Iterator::next();
has_peeked = false;//now the current value is not peeked yet
return value;
}
bool hasNext() const {
if(has_peeked) return true;
return Iterator::hasNext();
}
private:
bool has_peeked = false;
int value;
};
还有个解法是利用Iterator 的copy constructor.
Iterator(*this) makes a copy of current iterator, then call next on the copied iterator to get the next value without affecting current iterator.
class PeekingIterator : public Iterator
{
public:
PeekingIterator(const vector<int> &nums) : Iterator(nums)
{
}
int peek()
{
return Iterator(*this).next();
}
int next()
{
return Iterator::next();
}
bool hasNext() const
{
return Iterator::hasNext();
}
};