#ifndef __LIST_H #define __LIST_H #include template struct Node { T *data; Node *next; }; // A linked list. Internal iterator only! // Usage is List - the list will store Object* // If own is 1, the list will call delete on all objects when destroyed template class List { public: List() : first(NULL), next_node(NULL) {} ~List(); void insert (T* x); void remove (T* x); inline T* rewind(); inline T* next(); T* operator[] (int no); int count() const; private: Node *first; Node *next_node; }; template List::~List() { Node *n_next; for (Node *n = first; n; n = n_next) { n_next = n->next; if (own) delete n->data; delete n; } } template int List::count() const { int i = 0; for (Node *n = first; n; n = n->next) i++; return i; } template T* List::operator[] (int no) { int i = 0; for (Node *n = first; n; n = n->next, i++) if (i == no) return n->data; return NULL; } template T* List::next() { Node *p = next_node; if (p) next_node = next_node->next; return p ? p->data : 0; } template void List::remove(T *x) { Node *p; assert(first != NULL); if (first->data == x) { p = first; first = first->next; } else { Node *prev; for (prev = first; prev && prev->next->data != x; prev = prev->next) ; assert(prev); assert(prev->next->data == x); p = prev->next; prev->next = prev->next->next; } if (next_node && next_node->data == x) next_node = p->next; delete p; } template T* List::rewind() { if (first) next_node = first->next; else next_node = 0; return first ? first->data : 0; } template void List::insert (T* x) { Node *node = new Node; Node *prev; node->data = x; for (prev = first; prev && prev->next;prev = prev->next) ; if (!prev) { node->next = first; first = node; } else { prev->next = node; node->next = 0; } } #endif