00001
00002
00003 #ifndef __LIST_H
00004 #define __LIST_H
00005
00006 #include <stdlib.h>
00007 #include <stdio.h>
00008
00009 namespace esg {
00010
00016 template <class Type> class List {
00017 protected:
00018 struct Node {
00019 Node* pnext;
00020 Type* pitem;
00021 };
00022
00023 Node* _phandler;
00024 Node* _pact;
00025 unsigned _length;
00026
00027 public:
00032 List<Type> () { _pact = (_phandler = NULL); _length = 0; }
00033
00037 ~List<Type> () {
00038 Node* n = _phandler; while(n) { Node* t=n; n=n->pnext; delete t; }
00039 }
00040
00046 void append (Type* i) {
00047 Node* n = new Node;
00048 n->pitem = i;
00049 n->pnext = _phandler;
00050 _phandler = n;
00051 _length++;
00052 }
00053
00060 void append (List<Type>& src) {
00061 if (_phandler) {
00062 Node * n = _phandler;
00063 while (n->pnext) n = n->pnext;
00064 n->pnext = src._phandler;
00065 } else
00066 _phandler = src._phandler;
00067 _length += src._length;
00068 src._length = 0;
00069 src._phandler = (src._pact = NULL);
00070 }
00071
00080 Type* remove (Type* i) {
00081 if (!_phandler || !i) return NULL;
00082 if (_phandler->pitem == i) {
00083 Type* r = _phandler->pitem;
00084 Node* t = _phandler;
00085 if (_pact == _phandler) _pact = _phandler->pnext;
00086 _phandler = _phandler->pnext;
00087 delete t;
00088 _length--;
00089 return r;
00090 }
00091 Node* f = _phandler;
00092 Node* s = _phandler->pnext;
00093 while (s && s->pitem != i) { f = s; s = s->pnext; }
00094 if (s) {
00095 f->pnext = s->pnext;
00096 Type* r = s->pitem;
00097 if (_pact == s) _pact = s->pnext;
00098 delete s;
00099 _length--;
00100 return r;
00101 }
00102 return NULL;
00103 }
00104
00108 unsigned length () const { return _length; }
00109
00113 bool empty () const { return ! _length; }
00114
00121 Type* firstItem () {
00122 _pact=_phandler;
00123 return ((_pact) ? _pact->pitem : NULL);
00124 }
00125
00131 Type* nextItem () {
00132 if (_pact && _pact->pnext) {
00133 _pact=_pact->pnext;
00134 return _pact->pitem;
00135 } else
00136 return NULL;
00137 }
00138
00144 Type* actualItem () { return ((_pact) ? _pact->pitem : NULL); }
00145
00154 Type* iThItem (unsigned i, bool setAct) {
00155 if (i >= _length) return NULL;
00156 Node* n = _phandler;
00157 for (unsigned j = 0; j < i; j++) n = n->pnext;
00158 if (setAct) _pact = n;
00159 return n->pitem;
00160 }
00161
00165 void dropAll (void) {
00166 while (remove(firstItem()));
00167 }
00168
00172 void deleteAll (void) {
00173 Type * t = remove(firstItem());
00174 while (t) { delete t; t = remove(firstItem()); }
00175 }
00176
00180 void __debug() {
00181 if (!_phandler) { fprintf(stderr,"List: No items stored\n"); return; }
00182 fprintf(stderr,"List: stored items:\n");
00183 for (Node* n=_phandler;n;n=n->pnext) n->pitem->__debug();
00184 }
00185 };
00186
00187 };
00188
00189 #endif // __LIST_H