【leetcode】284. Peeking Iterator
题目:
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& 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;}
};
参考:
https://leetcode.com/problems/peeking-iterator/discuss/72598/Another-C%2B%2B-solution-with-one-line-in-peek()-and-hasNext()-AC
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
