-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathLinkedList.h
More file actions
121 lines (107 loc) · 1.93 KB
/
LinkedList.h
File metadata and controls
121 lines (107 loc) · 1.93 KB
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
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
template<typename T>
class LinkedList {
public:
LinkedList():last(NULL),first(NULL),length(0){}
struct Node {
T* item;
Node* next;
Node* prev;
Node(T* item):item(item),next(NULL),prev(NULL){}
};
void Add(T* item) {
Node* n = new Node(item);
if (last == NULL) {
last = n;
first = n;
} else {
last->next = n;
n->prev = last;
last = n;
}
length += 1;
}
Node* GetItem(T* item) {
Node* n = first;
while(n != NULL) {
if (n->item == item)
return n;
n = n->next;
}
return NULL;
}
void Remove(T* item) {
Node* n = GetItem(item);
Remove(n);
}
Node* Remove(Node* n) {
if (!n)
return NULL;
if (first == n)
first = n->next;
if (last == n)
last = n->prev;
if (n->prev)
n->prev->next = n->next;
if (n->next)
n->next->prev = n->prev;
Node* ret = n->next;
delete n;
length -= 1;
return ret;
}
Node* last;
Node* first;
uint16_t length;
};
template<typename NodeType>
class LinkedList2{
public:
LinkedList2():last(NULL),first(NULL),length(0){}
void Add(NodeType* item) {
if (last == NULL) {
last = item;
first = item;
item->next = NULL;
item->prev = NULL;
} else {
last->next = item;
item->prev = last;
item->next = NULL;
last = item;
}
length += 1;
}
template<typename SearchParamType>
NodeType* Find(SearchParamType input, bool(*search_func)(const NodeType*, SearchParamType))
{
NodeType* current = first;
while (current != NULL) {
if (search_func(current, input))
return current;
current = current->next;
}
return NULL;
}
NodeType* Remove(NodeType* n) {
if (!n)
return NULL;
if (first == n)
first = n->next;
if (last == n)
last = n->prev;
if (n->prev)
n->prev->next = n->next;
if (n->next)
n->next->prev = n->prev;
NodeType* ret = n->next;
delete n;
length -= 1;
return ret;
}
NodeType* last;
NodeType* first;
uint16_t length;
};
#endif