/* mylist.h */
template <class T>
class TList {
private:
struct TNode {
T *data;
TNode *prev, *next;
} *fFirst, *fLast;
TNode *find(T *);
public:
TList();
~TList();
void addAfter(T *, T *after);
T *remove(T *);
void clear();
T *prev(T *);
T *next(T *);
T *first();
T *last();
};
/* mylist.cpp */
#include <stddef.h>
#include "mylist.h"
template <class T>
TList<T>::TList() {
fFirst = fLast = NULL;
}
template <class T>
TList<T>::~TList() {
clear();
}
template <class T>
TList<T>::TNode *TList<T>::find(T *e) {
TNode *n = fFirst;
while (n) {
if (n->data == e) return n;
n = n->next;
}
return NULL;
}
template <class T>
void TList<T>::addAfter(T *e, T *after) {
if (!e) return;
if (!after) {
TNode *n = new TNode;
n->data = e;
n->prev = NULL;
n->next = fFirst;
if (fFirst) fFirst->prev = n;
else fLast = n;
fFirst = n;
} else {
TNode *n = new TNode, *aftern = find(after);
if (!aftern) return;
n->data = e;
n->prev = aftern;
n->next = aftern->next;
aftern->next->prev = n;
aftern->next = n;
if (aftern == fLast) fLast = n;
}
}
template <class T>
T *TList<T>::remove(T *e) {
TNode *n = find(e);
if (!n) return NULL;
if (n == fFirst) {
fFirst = n->next;
fFirst->prev = NULL;
} else if (n == fLast) {
fLast = n->prev;
fLast->next = NULL;
} else {
n->prev->next = n->next;
n->next->prev = n->prev;
}
delete n;
return e;
}
template <class T>
void TList<T>::clear() {
TNode *n = fFirst;
while (n) {
delete n->data;
TNode *tmp = n;
n = n->next;
delete tmp;
}
fFirst = fLast = NULL;
}
template <class T>
T *TList<T>::prev(T *e) {
TNode *n = find(e);
if (!n || !(n->prev)) return NULL;
return n->prev->data;
}
template <class T>
T *TList<T>::next(T *e) {
TNode *n = find(e);
if (!n || !(n->next)) return NULL;
return n->next->data;
}
template <class T>
T *TList<T>::first() {
return fFirst->data;
}
template <class T>
T *TList<T>::last() {
return fLast->data;
}