-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_list.h
80 lines (68 loc) · 1.79 KB
/
custom_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
// Will be extended as the need arose
template<typename T, T* (T::*GetNext)() const, void (T::*SetNext)(T*)>
class CustomList {
public:
CustomList() = default;
explicit CustomList(T* head) : head_(head) {}
bool Empty() const {
return head_ == nullptr;
}
void Clear() {
head_ = nullptr;
}
T& Front() {
ASSERT(head_ != nullptr);
return *head_;
}
void PushFront(T& item) {
(item.*SetNext)(head_);
head_ = &item;
}
void PopFront() {
ASSERT(head_ != nullptr);
head_ = GetNextHelper(head_);
}
void EraseAfter(T* prev, T* current)
{
if (current == head_) {
head_ = GetNextHelper(current);
} else {
SetNextHelper(prev, GetNextHelper(current));
}
}
template <typename Predicate>
bool RemoveIf(Predicate pred)
{
bool found = false;
auto prev = head_;
for (auto current = head_; current != nullptr; current = GetNextHelper(current)) {
if (pred(*current)) {
found = true;
EraseAfter(prev, current);
current = prev;
} else {
prev = current;
}
}
return found;
}
void Splice(CustomList& other) {
if (Empty()) {
head_ = other.head_;
} else {
T *last = head_;
for (; last->GetNextWait() != nullptr; last = GetNextHelper(last)) {}
SetNextHelper(last, other.head_);
}
other.Clear();
}
private:
ALWAYS_INLINE T* GetNextHelper(T* item) const {
return ((*item).*GetNext)();
}
ALWAYS_INLINE void SetNextHelper(T* prev, T* item) {
((*prev).*SetNext)(item);
}
private:
T* head_{nullptr};
};