-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlist.h
86 lines (62 loc) · 1.42 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
//
// Created by konstantin on 08.06.24.
//
#pragma once
#include <cassert>
#include <cstdint>
namespace NComponents {
template <class T>
class Node {
public:
using TNode = Node<T>;
TNode* Next() { return next_; }
T* Cast() { return static_cast<T*>(this); }
void LinkAfter(TNode* prev) { prev->next_ = this; }
private:
TNode* next_{nullptr};
};
template <class T>
class IntrusiveList {
public:
using Node = Node<T>;
IntrusiveList() = default;
~IntrusiveList() noexcept { assert(IsEmpty()); }
IntrusiveList(const IntrusiveList<T>& o)
: size_(o.size_), head_(o.head_), tail_(o.tail_) {}
bool IsEmpty() const { return 0 == size_; }
void Clear() {
head_ = nullptr;
tail_ = nullptr;
size_ = 0;
}
void Push(Node* node) {
assert(node);
if (head_) {
node->LinkAfter(tail_);
} else {
head_ = node;
}
tail_ = node;
size_++;
}
T* Pop() {
if (IsEmpty()) {
return nullptr;
}
Node* p = head_;
if (1 == size_) {
head_ = nullptr;
tail_ = nullptr;
} else {
head_ = p->Next();
}
size_--;
return p->Cast();
}
std::size_t Size() const { return size_; }
private:
std::size_t size_{0};
Node* head_{nullptr};
Node* tail_{nullptr};
};
} // namespace NComponents