-
Notifications
You must be signed in to change notification settings - Fork 0
/
List.h
127 lines (105 loc) · 1.78 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#pragma once
namespace chess {
template <class T>
struct ListNode
{
T* item;
ListNode<T>* prev;
ListNode<T>* next;
ListNode(T* _item) {
item = _item;
prev = nullptr;
next = nullptr;
}
~ListNode() {
}
};
template <class T>
struct List {
ListNode<T>* nodes;
unsigned char length;
List<T>() {
nodes = nullptr;
length = 0;
}
void append(T* _item) {
ListNode<T>* node = new ListNode<T>(_item);
if (!nodes) {
nodes = node;
}
else {
ListNode<T>* ptr = nodes;
while (ptr->next) {
ptr = ptr->next;
}
ptr->next = node;
node->prev = ptr;
}
++length;
}
void remove(ListNode<T>* node) {
if (node->next) {
node->next->prev = node->prev;
}
if (node->prev) {
node->prev->next = node->next;
}
else {
// this is first node
nodes = node->next;
}
node->prev = nullptr;
node->next = nullptr;
delete node;
node = nullptr;
--length;
}
void remove(T* item) {
ListNode<T>* node = nodes;
while (node) {
if (node->item == item) {
remove(node);
break;
}
node = node->next;
}
}
void replace(T* srcItem, T* dstItem) {
ListNode<T>* node = nodes;
while (node) {
if (node->item == srcItem) {
node->item = dstItem;
break;
}
node = node->next;
}
}
void clear() {
delete nodes;
nodes = nullptr;
length = 0;
}
T* getAt(unsigned char pos) {
if (pos >= length) {
return nullptr;
}
unsigned char i = 0;
ListNode<T>* node = nodes;
bool found = false;
for (i = 0; i < pos; ++i) {
node = node->next;
}
return node->item;
}
~List() {
ListNode<T>* p = nodes;
ListNode<T>* q;
while (p) {
q = p->next;
delete p;
p = q;
}
nodes = nullptr;
}
};
}