|
| 1 | +/* |
| 2 | +Peeking Iterator |
| 3 | +=============== |
| 4 | +
|
| 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 | +Assume that the iterator is initialized to the beginning of the list: [1,2,3]. |
| 9 | +
|
| 10 | +Call next() gets you 1, the first element in the list. |
| 11 | +Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. |
| 12 | +You call next() the final time and it returns 3, the last element. |
| 13 | +Calling hasNext() after that should return false. |
| 14 | +Follow up: How would you extend your design to be generic and work with all types, not just integer? |
| 15 | +
|
| 16 | +
|
| 17 | +Hint #1 |
| 18 | +Think of "looking ahead". You want to cache the next element. |
| 19 | +
|
| 20 | +Hint #2 |
| 21 | +Is one variable sufficient? Why or why not? |
| 22 | +
|
| 23 | +Hint #3 |
| 24 | +Test your design with call order of peek() before next() vs next() before peek(). |
| 25 | +
|
| 26 | +Hint #4 |
| 27 | +For a clean implementation, check out Google's guava library source code. |
| 28 | +*/ |
| 29 | + |
| 30 | +/* |
| 31 | + * Below is the interface for Iterator, which is already defined for you. |
| 32 | + * **DO NOT** modify the interface for Iterator. |
| 33 | + * |
| 34 | + * class Iterator { |
| 35 | + * struct Data; |
| 36 | + * Data* data; |
| 37 | + * Iterator(const vector<int>& nums); |
| 38 | + * Iterator(const Iterator& iter); |
| 39 | + * |
| 40 | + * // Returns the next element in the iteration. |
| 41 | + * int next(); |
| 42 | + * |
| 43 | + * // Returns true if the iteration has more elements. |
| 44 | + * bool hasNext() const; |
| 45 | + * }; |
| 46 | + */ |
| 47 | + |
| 48 | +class PeekingIterator : public Iterator |
| 49 | +{ |
| 50 | +public: |
| 51 | + PeekingIterator(const vector<int> &nums) : Iterator(nums) |
| 52 | + { |
| 53 | + // Initialize any member here. |
| 54 | + // **DO NOT** save a copy of nums and manipulate it directly. |
| 55 | + // You should only use the Iterator interface methods. |
| 56 | + } |
| 57 | + |
| 58 | + // Returns the next element in the iteration without advancing the iterator. |
| 59 | + int peek() |
| 60 | + { |
| 61 | + return Iterator(*this).next(); |
| 62 | + } |
| 63 | + |
| 64 | + // hasNext() and next() should behave the same as in the Iterator interface. |
| 65 | + // Override them if needed. |
| 66 | + // int next() { |
| 67 | + // } |
| 68 | + |
| 69 | + // bool hasNext() const { |
| 70 | + // } |
| 71 | +}; |
0 commit comments