Powered By GitBook
284.Peeking Iterator

284.Peeking Iterator

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