-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list.hh
124 lines (103 loc) · 2.58 KB
/
linked_list.hh
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
115
116
117
118
119
120
121
122
123
124
#ifndef KS_LINKED_LIST_HH
#define KS_LINKED_LIST_HH
#include <stddef.h>
template <class T>
struct double_linked_list_node
{
double_linked_list_node* prev {nullptr};
double_linked_list_node* next {nullptr};
T data {};
};
template <class T>
inline T& data(double_linked_list_node<T>* node)
{
return node->data;
}
template <class T>
inline const T& data(const double_linked_list_node<T>* node)
{
return node->data;
}
template <class T>
inline double_linked_list_node<T>* next(double_linked_list_node<T>* node)
{
return node->next;
}
template <class T>
inline double_linked_list_node<T>* prev(double_linked_list_node<T>* node)
{
return node->prev;
}
template <class T>
inline double_linked_list_node<T>* first(double_linked_list_node<T>* node)
{
while (node)
{
if (!prev(node)) return node;
node = prev(node);
}
return nullptr;
}
template <class T>
inline double_linked_list_node<T>* last(double_linked_list_node<T>* node)
{
while (node)
{
if (!next(node)) return node;
node = next(node);
}
return nullptr;
}
template <class T>
inline size_t size(double_linked_list_node<T>* node)
{
size_t len {};
for (node = first(node); node != nullptr; node = next(node))
++len;
return len;
}
template <class T>
inline void append(double_linked_list_node<T>* node, double_linked_list_node<T>* new_node)
{
node = last(node);
node->next = new_node;
new_node->prev = node;
}
//template <class T>
//double_linked_list_node<T>* make_double_linked_list_node(const T& data)
//{
// double_linked_list_node<T>* node = new double_linked_list_node<T>();
// node->data = data;
// return node;
//}
template <class T, class U = T>
inline double_linked_list_node<T>* make_double_linked_list_node(const U& data)
{
double_linked_list_node<T>* node = new double_linked_list_node<T>();
node->data = dynamic_cast<T>(data);
return node;
}
//template <class T>
//void append(double_linked_list_node<T>* node, const T& data)
//{
// double_linked_list_node<T>* new_node = make_double_linked_list_node(data);
// append(node, new_node);
//}
template <class T, class U = T>
inline void append(double_linked_list_node<T>* node, const U& data)
{
double_linked_list_node<T>* new_node = make_double_linked_list_node<T>(data);
append(node, new_node);
}
template <class T>
inline void deallocate(double_linked_list_node<T>* node)
{
node = first(node);
while (node)
{
double_linked_list_node<T>* temp = node;
node = next(node);
delete temp;
}
}
#endif // KS_LINKED_LIST_HH