实现一个迭代器支持peek,next,hasnext。
其中next和hasnext直接使用继承来的操作即可;peek要求返回数值又不删除它,可以用一个临时变量的next实现。
// 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.
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
<span style="white-space:pre"> </span>Iterator it(*this);
<span style="white-space:pre"> </span>return it.next();
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
};