Skip to content

Commit 77be572

Browse files
committed
Enable the main function work by implementing the iterator interface.
Enable the main function work by implementing the iterator interface.
1 parent 477f0fb commit 77be572

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include <iostream>
2+
#include <queue>
3+
#include <vector>
4+
#include <assert.h>
5+
#include <algorithm>
6+
using namespace std;
7+
8+
class Iterator {
9+
const vector<int>* nums;
10+
int index;
11+
public:
12+
Iterator(const vector<int>& nums) {
13+
this->nums = &nums;
14+
this->index = 0;
15+
}
16+
Iterator(const Iterator& iter);
17+
18+
// Returns the next element in the iteration.
19+
int next() {
20+
return (*nums)[index++];
21+
}
22+
23+
// Returns true if the iteration has more elements.
24+
bool hasNext() const {
25+
return index < (*nums).size();
26+
}
27+
};
28+
29+
class PeekingIterator : public Iterator {
30+
private:
31+
int nextElement;
32+
bool flag;
33+
public:
34+
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
35+
// Initialize any member here.
36+
// **DO NOT** save a copy of nums and manipulate it directly.
37+
// You should only use the Iterator interface methods.
38+
flag = Iterator::hasNext();
39+
if (flag) {
40+
nextElement = Iterator::next();
41+
}
42+
}
43+
44+
// Returns the next element in the iteration without advancing the iterator.
45+
int peek() {
46+
return nextElement;
47+
}
48+
49+
// hasNext() and next() should behave the same as in the Iterator interface.
50+
// Override them if needed.
51+
int next() {
52+
int ret = nextElement;
53+
flag = Iterator::hasNext();
54+
if (flag) {
55+
nextElement = Iterator::next();
56+
}
57+
return ret;
58+
}
59+
60+
bool hasNext() const {
61+
return flag;
62+
}
63+
};
64+
65+
// Test
66+
int main()
67+
{
68+
/** 用gcc/g++编译, 需要用这种方式初始化vector:
69+
*/
70+
int a[3] = {1, 2, 3};
71+
vector<int> nums(a, a + 3);
72+
73+
PeekingIterator peekingIterator(nums);
74+
assert(1 == peekingIterator.next());
75+
assert(2 == peekingIterator.peek());
76+
assert(2 == peekingIterator.next());
77+
assert(3 == peekingIterator.next());
78+
assert(!peekingIterator.hasNext());
79+
80+
cout << "OK~" << endl;
81+
82+
return 0;
83+
}

0 commit comments

Comments
 (0)