|
| 1 | +[To Index](/index.md) |
| 2 | +--- |
| 3 | +# 284.Peeking Iterator |
| 4 | +难度:Medium |
| 5 | +> 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()`. |
| 6 | +
|
| 7 | +Example: |
| 8 | + |
| 9 | +``` |
| 10 | +Assume that the iterator is initialized to the beginning of the list: [1,2,3]. |
| 11 | +
|
| 12 | +Call next() gets you 1, the first element in the list. |
| 13 | +Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. |
| 14 | +You call next() the final time and it returns 3, the last element. |
| 15 | +Calling hasNext() after that should return false. |
| 16 | +``` |
| 17 | + |
| 18 | +Follow up: How would you extend your design to be generic and work with all types, not just integer? |
| 19 | + |
| 20 | +We can set a right value stands for next value, a bool stands for hasNext() function. |
| 21 | +Codes are as follows: |
| 22 | + |
| 23 | +``` |
| 24 | +// Below is the interface for Iterator, which is already defined for you. |
| 25 | +// **DO NOT** modify the interface for Iterator. |
| 26 | +
|
| 27 | +class Iterator { |
| 28 | + struct Data; |
| 29 | + Data* data; |
| 30 | +public: |
| 31 | + Iterator(const vector<int>& nums); |
| 32 | + Iterator(const Iterator& iter); |
| 33 | + virtual ~Iterator(); |
| 34 | + // Returns the next element in the iteration. |
| 35 | + int next(); |
| 36 | + // Returns true if the iteration has more elements. |
| 37 | + bool hasNext() const; |
| 38 | +}; |
| 39 | +
|
| 40 | +
|
| 41 | +class PeekingIterator : public Iterator { |
| 42 | +int right; |
| 43 | +bool flag; |
| 44 | +public: |
| 45 | + PeekingIterator(const vector<int>& nums) : Iterator(nums) { |
| 46 | + // Initialize any member here. |
| 47 | + // **DO NOT** save a copy of nums and manipulate it directly. |
| 48 | + // You should only use the Iterator interface methods. |
| 49 | + flag= Iterator::hasNext(); |
| 50 | + right = Iterator::next(); |
| 51 | + } |
| 52 | +
|
| 53 | + // Returns the next element in the iteration without advancing the iterator. |
| 54 | + int peek() { |
| 55 | + return right; |
| 56 | + } |
| 57 | +
|
| 58 | + // hasNext() and next() should behave the same as in the Iterator interface. |
| 59 | + // Override them if needed. |
| 60 | + int next() { |
| 61 | + int cur=right; |
| 62 | + flag = Iterator::hasNext(); |
| 63 | + if(flag) |
| 64 | + { |
| 65 | + right = Iterator::next(); |
| 66 | + } |
| 67 | + return cur; |
| 68 | + } |
| 69 | +
|
| 70 | + bool hasNext() const { |
| 71 | + return flag; |
| 72 | + } |
| 73 | +}; |
| 74 | +``` |
| 75 | +> 执行用时 :8 ms, 在所有 C++ 提交中击败了64.25%的用户 |
| 76 | +内存消耗 :9.9 MB, 在所有 C++ 提交中击败了38.30%的用户 |
0 commit comments