-
Notifications
You must be signed in to change notification settings - Fork 4
/
set.hpp
114 lines (98 loc) · 1.88 KB
/
set.hpp
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#ifndef SET_H
#define SET_H
#include "stdint.h"
#include "node.hpp"
class Set
{
public:
Node *head;
Set()
{
head = nullptr;
}
~Set()
{
empty();
}
bool add(uint8_t data)
{
if (head == nullptr)
{
head = new Node(data);
}
else
{
Node *curr = head;
while (curr->next != nullptr)
{
if (curr->data == data)
return false;
curr = curr->next;
}
if (curr->data == data)
return false;
curr->next = new Node(data);
}
return true;
}
bool remove(uint8_t data)
{
if (head == nullptr)
return false;
Node *curr = head;
Node *before = head;
while (curr->next != nullptr) {
if (curr->data == data) {
// 找到了
// 删除该节点
if (curr == head) {
head = curr->next;
} else {
before->next = curr->next;
}
delete curr;
return true;
} else {
// 找不到, 去找下一个节点
before = curr;
curr = curr->next;
}
}
if (curr->data == data) {
if (curr == head)
head = curr->next;
else
before->next = curr->next;
delete curr;
return true;
}
return false;
}
void foreach (void (*callback)(uint8_t))
{
if (head == nullptr) return;
Node *curr = head;
while (curr->next != nullptr)
{
(*callback)(curr->data);
curr = curr->next;
}
(*callback)(curr->data);
}
void empty()
{
if (head == nullptr)
return;
Node *curr = head;
Node *before;
while (curr->next != nullptr)
{
before = curr;
curr = curr->next;
delete before;
}
delete curr;
head = nullptr;
}
};
#endif