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().html
Example:java
Assume that the iterator is initialized to the beginning of the list: . Call gets you 1, the first element in the list. Now you call and it returns 2, the next element. Calling after that still return 2. You call the final time and it returns 3, the last element. Calling after that should return false.[1,2,3]next()peek()next()next()hasNext()
Hint:git
peek()
before next()
vs next()
before peek()
.Follow up: How would you extend your design to be generic and work with all types, not just integer?github
这道题让咱们实现一个顶端迭代器,在普通的迭代器类Iterator的基础上增长了peek的功能,就是返回查看下一个值的功能,可是不移动指针,next()函数才会移动指针,那咱们能够定义一个变量专门来保存下一个值,再用一个bool型变量标记是否保存了下一个值,再调用原来的一些成员函数,就能够实现这个顶端迭代器了,参见代码以下:函数
解法一:post
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) { _flag = false; } int peek() { if (!_flag) _value = Iterator::next(); _flag = true; return _value; } int next() { if (!_flag) return Iterator::next(); _flag = false; return _value; } bool hasNext() const { return _flag || Iterator::hasNext(); } private: int _value; bool _flag; };
这道题主要的考点就是peek函数,由于这个是默认的迭代器不具有的功能。咱们其实能够使用一个小trick来实现peek功能,因为peek是要暗中观察一下下一个元素,可是迭代器并不真正移动到下一个,那么咱们实际上是能够建立一个副本,而后让副本移动到下一个,并返回,因为是局部变量,副本在调用结束后也会被销毁,因此并无任何内存问题,能够说是一种至关聪明的解法了,参见代码以下:this
解法二:google
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) {} int peek() { return Iterator(*this).next(); } int next() { return Iterator::next(); } bool hasNext() const { return Iterator::hasNext(); } };
相似题目:url
Binary Search Tree Iteratorspa
参考资料:
https://leetcode.com/problems/peeking-iterator/