forked from rising-entropy/Leetcode-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeeking_iterator.cpp
More file actions
28 lines (23 loc) · 1012 Bytes
/
Peeking_iterator.cpp
File metadata and controls
28 lines (23 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class PeekingIterator : public Iterator {
int next_val; // keep a variable for storing the "next value" for use in "peek" function
bool iter_hasnext; // for storing the "has next value"
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
iter_hasnext=Iterator::hasNext(); // store current has_next value
if (iter_hasnext)
next_val = Iterator::next(); // store the "next_val" for "future" use in "peek" function
}
int peek() {
return next_val; // return current next_val
}
int next() {
int curr_next = next_val; // store the current next for returning
iter_hasnext=Iterator::hasNext(); // change the iter_hasnext variable
if (iter_hasnext)
next_val = Iterator::next(); // change the next_val and move the iterator to next position
return curr_next; // return the previously stored current next
}
bool hasNext() const {
return iter_hasnext; // return current iter_hashnext value
}
};