-
Notifications
You must be signed in to change notification settings - Fork 2
/
list.cc
73 lines (57 loc) · 1.46 KB
/
list.cc
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
using namespace std;
class List {
struct Node {
int data;
Node *next;
Node(int data, Node *next):data{data}, next{next}{}
~Node(){delete next;}
};
Node *theList = nullptr;
public:
class Iterator{
Node *p;
Iterator(Node *p):p{p}{}
public:
friend class List;
int &operator*() { return p->data;}
Iterator &operator++() { p = p->next; return *this; }
bool operator!=(const Iterator &other) const { return p!= other.p; }
};
List &addToFront(int n) { theList = new Node{n, theList}; return *this; }
int ith(int i) {
Node *cur = theList;
for (int j = 0; j < i; ++j) {
cur = cur->next;
}
return cur->data;
}
~List() { delete theList;}
Iterator begin(){ return Iterator(theList); }
Iterator end(){ return Iterator(nullptr );};
};
int main() {
List l;
l.addToFront(1).addToFront(2).addToFront(3);
cout << l.ith(0) << endl;
cout << l.ith(1) << endl;
cout << l.ith(2) << endl;
cout << "---" << endl;
for(List::Iterator it = l.begin(); it != l.end(); ++it) {
cout << *it << endl;
}
cout << "---" << endl;
for(auto it = l.begin(); it != l.end(); ++it) {
cout << *it << endl;
}
cout << "---" << endl;
for(const auto i:l) {
cout << i << endl;
}
cout << "---" << endl;
for(auto &i:l) {
i++; // mutate the values because it is a reference
cout << i << endl;
}
return 0;
}