-
Notifications
You must be signed in to change notification settings - Fork 6
/
LinkedList.h
118 lines (108 loc) · 1.86 KB
/
LinkedList.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
#ifndef LINKEDLISTITEM_H_
#define LINKEDLISTITEM_H_
#include <Arduino.h>
template<typename T>
class LinkedListItem
{
template<typename U>
friend class LinkedList;
public:
LinkedListItem(T i) : m_item(i), m_next(NULL) {}
~LinkedListItem()
{
#ifdef CONSOLE
if (m_item)
{
CONSOLE.println("~LinkedListItem - m_item is not NULL");
}
if (m_next)
{
CONSOLE.println("~LinkedListItem = m_next is not NULL");
}
#endif
}
inline T getItem() { return m_item; }
inline LinkedListItem<T>* getNext() { return m_next; }
private:
T m_item;
LinkedListItem<T>* m_next;
};
template<typename T>
class LinkedList
{
public:
LinkedList() :
m_first(NULL)
{
}
~LinkedList()
{
while (m_first)
{
#ifdef CONSOLE
CONSOLE.print("~LinkedList - items not cleaned up");
if (m_first->m_item)
{
CONSOLE.print(" and item content is not NULL.");
}
CONSOLE.println();
#endif
remove(m_first->m_item);
}
}
void add(T item)
{
LinkedListItem<T>* container = new LinkedListItem<T>(item);
if (m_first == NULL)
{
m_first = container;
}
else
{
for (LinkedListItem<T>* i = m_first; i; i = i->m_next)
{
if (!i->m_next)
{
i->m_next = container;
break;
}
}
}
}
T remove(T item)
{
LinkedListItem<T>* prev = NULL;
for (LinkedListItem<T>* i = m_first; i; prev = i, i = i->m_next)
{
if (i->m_item == item)
{
if (i == m_first)
{
m_first = i->m_next;
}
else if (prev)
{
prev->m_next = i->m_next;
}
else
{
#if defined CONSOLE
CONSOLE.println("LinkedList: unexpected case");
#endif
}
i->m_item = NULL;
i->m_next = NULL;
delete i;
return item;
}
}
#if defined CONSOLE
CONSOLE.println("LinkedList: failed to remove item!");
#endif
return NULL;
}
inline LinkedListItem<T>* getFirst() { return m_first; }
private:
LinkedListItem<T>* m_first;
};
#endif