Code /* tlist.h CIS 250 David Klick 2010-03-15 Templated linked list specification */ #ifndef __TLIST_H__ #define __TLIST_H__ #include #include #include using std::cout; using std::endl; using std::string; using std::ostream; template class tlist { public: class node { public: T* data; node* next; }; private: node* head; int count; public: tlist(); ~tlist(); int length() const; void print() const; T* front() const; T* back() const; bool isEmpty() const; void add(T* val); bool remove(T* val); }; template tlist::tlist() { count = 0; head = NULL; } template tlist::~tlist() { while (head != NULL) { node* hold = head->next; delete head; head = hold; count--; } } template int tlist::length() const { return count; } template void tlist::print() const { node* pos = head; while (pos != NULL) { pos->data->print(); cout << " "; pos = pos->next; } cout << endl; } template T* tlist::front() const { if (head == NULL) throw string("Error: Accessing empty list"); return head->data; } template T* tlist::back() const { if (head == NULL) throw string("Error: Accessing empty list"); node* pos = head; while (pos->next != NULL) pos = pos->next; return pos->data; } template bool tlist::isEmpty() const { return head == NULL; } template void tlist::add(T* obj) { node* elephant = new node; assert (elephant != NULL); elephant->data = obj; elephant->next = NULL; if (head == NULL) { head = elephant; } else { node* pos = head; while (pos->next != NULL) pos = pos->next; pos->next = elephant; } count++; } template bool tlist::remove(T* obj) { if (head == NULL) return false; if (head->data->equals(obj)) { node *temp = head; head = head->next; delete temp; count--; return true; } node* prev = head; node* curr = prev->next; while (curr != NULL) { if (curr->data->equals(obj)) { prev->next = curr->next; delete curr; count--; return true; } else { prev = curr; curr = curr->next; } } return false; } #endif