感觉这道题主要考OOD和cpp的语法
坑:
1.怎么在派生类里面调用基类的非虚函数
2.hasnext()不能直接调用基类的hasnext(),因为如果peak了之后,基类的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 {
private:
bool peeked;
int val;
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.
peeked=false;
val=-1;
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
if(!peeked){
val=Iterator::next();
peeked=true;
}
return val;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
if(peeked){
peeked=false;
return val;
}
return Iterator::next();
}
bool hasNext() const {
if(peeked)
return true;
return Iterator::hasNext();
}
};
实话我自己做的时候纠结了半天越想越复杂,最后还是借鉴了别人的答案。