This repository has been archived by the owner on Apr 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
List.h
104 lines (87 loc) · 2.04 KB
/
List.h
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
//
// Created by MacBook on 2019-05-08.
//
#ifndef PROJECT_2_LIST_H
#define PROJECT_2_LIST_H
template<typename T>
class List {
public:
List() : l(nullptr) {
}
~List() {
if (l) {
Node *next;
Node *parent;
parent = l;
while (parent) {
next = parent->next;
delete parent;
parent = next;
}
}
}
struct Node {
Node() : next(nullptr) {
}
T value;
Node *next;
};
void push(T v) {
if (l == nullptr) {
l = new Node;
l->value = v;
} else {
auto parent = l;
while (parent->next) {
parent = parent->next;
}
parent->next = new Node;
parent->next->value = v;
}
}
void remove(T v) {
if (l->value == v) {
auto *next = l->next;
delete l;
l = next;
} else {
auto *parent = l;
while (parent->next) {
if (parent->next->value == v) {
Node *next = parent->next->next;
delete parent->next;
parent->next = next;
}
parent = parent->next;
}
}
}
template<typename PredicateT>
void remove_if(const PredicateT &predicate) {
if (!l) { return; }
if (predicate(l->value)) {
auto *next = l->next;
delete l;
l = next;
} else {
auto *parent = l;
while (parent->next) {
if (predicate(parent->next->value)) {
Node *next = parent->next->next;
delete parent->next;
parent->next = next;
}
parent = parent->next;
}
}
}
Node *begin() {
return l;
}
const Node *end() {
return nullptr;
}
private:
Node *l;
};
#endif //PROJECT_2_LIST_H