forked from brimshot/quickPatterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqpLinkedList.h
127 lines (89 loc) · 2.69 KB
/
qpLinkedList.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
#ifndef QUICK_PATTERNS_LIST_H
#define QUICK_PATTERNS_LIST_H
#include <Arduino.h>
/** A minimalist linked list implementation */
template <typename T>
struct qpListNode {
T *item;
qpListNode *next;
};
template <typename T>
class qpLinkedList {
private:
qpListNode <T> *firstElement = nullptr;
qpListNode <T> *lastElement = nullptr;
qpListNode <T> *currentElement = nullptr;
public:
~qpLinkedList() {
qpListNode <T> *cur = firstElement;
while(cur) {
qpListNode <T> *next = cur->next;
delete cur->item;
delete cur;
cur = next;
}
}
byte numElements = 0;
T *getItem(int index) {
qpListNode <T> *tmp = this->firstElement;
for(byte i = 0; i < index; i++)
tmp = tmp->next;
return tmp->item;
}
T *getLast() {
return this->lastElement->item;
}
T *append(T *item) {
if(! this->firstElement) {
this->firstElement = this->lastElement = new qpListNode<T>();
this->currentElement = this->firstElement;
} else {
this->lastElement->next = new qpListNode<T>();
this->lastElement = this->lastElement->next;
}
this->numElements++;
this->lastElement->item = item;
return item;
}
// Returns next item on each successive call, nullptr when no items left - resets for next iteration automatically
T *fetch() {
T *itemToReturn = nullptr;
if(this->currentElement) {
itemToReturn = this->currentElement->item;
this->currentElement = currentElement->next;
} else //reset for next iteration
this->currentElement = this->firstElement;
return itemToReturn;
}
// Removes an item from the linked list.
bool remove(T *itemToRemove) {
qpListNode <T> *current = this->firstElement;
qpListNode <T> *previous = nullptr;
while(current) {
if(current->item == itemToRemove) {
// If this node is currently marked as the "current node", update it.
if(this->currentElement == current) {
this->currentElement = current->next;
}
// update the previous node to point to the new item
if(previous) {
previous->next = current->next;
}
// Update the first/last items
if(current == this->firstElement) {
this->firstElement = previous;
}
if(current == this->lastElement) {
this->lastElement = current->next;
}
delete current->item;
delete current;
return true;
}
previous = current;
current = current->next;
}
return false;
}
};
#endif