list.cpp
1.5 KB
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
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <stddef.h>
class List {
struct BaseNode {
BaseNode* prev;
BaseNode* next;
};
struct Node : public BaseNode {
int data;
};
BaseNode FirstLast{.prev = &FirstLast, .next = &FirstLast};
public:
// List() {
// FirstLast.next = &FirstLast;
// FirstLast.prev = &FirstLast;
// };
~List()
{
BaseNode* ptr = FirstLast.next;
while (ptr != &FirstLast) {
BaseNode* next = ptr->next;
delete ptr;
ptr = next;
}
}
class Iterator {
BaseNode* ptr;
public:
Iterator(BaseNode* p) : ptr(p){};
int& operator*()
{
return static_cast<Node*>(ptr)->data;
}
Iterator& operator++()
{
ptr = ptr->next;
return *this;
}
bool operator!=(const Iterator& o)
{
return ptr != o.ptr;
}
friend class List;
};
void insert(Iterator i, int v)
{
Node* n = new Node;
n->prev = i.ptr->prev;
n->next = i.ptr;
i.ptr->prev->next = n;
i.ptr->prev = n;
n->data = v;
}
Iterator begin()
{
return Iterator(FirstLast.next);
};
Iterator end()
{
return Iterator(&FirstLast);
};
};
int main()
{
List c;
c.insert(c.begin(), 1);
c.insert(c.begin(), 2);
c.insert(c.begin(), 3);
for (auto i : c)
std::cout << i << std::endl;
}