题目:
Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be returned by the next call to 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;
* 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:
int next_elem;
bool next_exist;
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.
if (Iterator::hasNext()){
next_elem = Iterator::next();
next_exist = true;
}else{
next_exist = false;
}
}
// Returns the next element in the iteration without advancing the iterator.
int peek() {
return next_elem;
}
// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
int ret = next_elem;
if (Iterator::hasNext()){
next_elem = Iterator::next();
next_exist = true;
}else{
next_exist = false;
}
return ret;
}
bool hasNext() const {
return next_exist;
}
};