先自己写了个简单粗糙的,然后又看了提示中给的参考答案,模仿着写了一个
// 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.
peekedElement = Iterator::next();
hasPeeked = true;
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
if(!hasPeeked)
{
peekedElement = Iterator::next();
hasPeeked = true;
}
return peekedElement;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
if(hasPeeked)
{
hasPeeked = false;
return peekedElement;
}
else
{
return Iterator::next();
}
}
bool hasNext() const {
return hasPeeked || Iterator::hasNext();
}
private:
int peekedElement;
bool hasPeeked;
};
基本思路是,用变量hasPeeked判断peekedElement保存的是否为所需的元素,若是,则无需调用基类的next()函数,直接使用这个变量。如此一来,增加peek功能不影响时间复杂度。