[Leetcode] Peeking Iterator, Solution

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().

Here is an example. Assume that the iterator is initialized to the beginning of the list:  [1, 2, 3].
Call  next() gets you 1, the first element in the list.
Now you call  peek() and it returns 2, the next element. Calling  next() after that  still return 2.
You call  next() the final time and it returns 3, the last element. Calling  hasNext() after that should return false.

[Thoughts]
鏈表的一道設計題。next其實在這裏就是獲取頭元素的值,並移動到下一個元素。peek在這裏就是返回當前元素的值。

[Code]
1:  // Below is the interface for Iterator, which is already defined for you.  
2: // **DO NOT** modify the interface for Iterator.
3: class Iterator {
4: struct Data;
5: Data* data;
6: public:
7: Iterator(const vector<int>& nums);
8: Iterator(const Iterator& iter);
9: virtual ~Iterator();
10: // Returns the next element in the iteration.
11: int next();
12: // Returns true if the iteration has more elements.
13: bool hasNext() const;
14: };
15: class PeekingIterator : public Iterator {
16: public:
17: PeekingIterator(const vector<int>& nums) : Iterator(nums) {
18: // Initialize any member here.
19: // **DO NOT** save a copy of nums and manipulate it directly.
20: // You should only use the Iterator interface methods.
21: this->length = nums.size();
22: this->nums = &nums;
23: }
24: // Returns the next element in the iteration without advancing the iterator.
25: int peek() {
26: if(currentIndex < length) {
27: return (*this->nums)[currentIndex];
28: }
29: return -1;
30: }
31: // hasNext() and next() should behave the same as in the Iterator interface.
32: // Override them if needed.
33: int next() {
34: if(currentIndex < length) {
35: currentIndex ++;
36: return (*this->nums)[currentIndex-1];
37: }
38: return -1;
39: }
40: bool hasNext() const {
41: return currentIndex < length;
42: }
43: private:
44: int currentIndex = 0;
45: int length = 0;
46: const vector<int>* nums = NULL;
47: };

github: https://github.com/codingtmd/leetcode/blob/master/src/Peeking_Iterator.cpp
相關文章
相關標籤/搜索