/* tlist.h CIS 250 2008-03-14 David Klick Implementation of templated (parameterized) tlist class. */ #ifndef __TLIST_H_ #define __TLIST_H_ #include #include #include using std::cout; using std::endl; using std::string; template class tlist { private: struct node { T* data; node* next; }; protected: node* head; public: tlist(); ~tlist(); int length() const; T* front() const; T* back() const; bool isEmpty() const; void add(T* obj); bool remove(T* obj); void print() const; T* get(const int ndx) const; }; template tlist::tlist() { head = NULL; } template tlist::~tlist() { while (head != NULL) { node* p = head->next; delete head; head = p; } } template int tlist::length() const { int count = 0; node* p = head; while (p != NULL) { count++; p = p->next; } return count; } template void tlist::print() const { node* p = head; while (p != NULL) { p->data->print(); p = p->next; } cout << endl; } template T* tlist::front() const { if (head == NULL) throw string("Error: Attempt to access first item in empty list"); return head->data; } template T* tlist::back() const { node* current = head; if (head == NULL) throw string("Error: Attempt to access last item in empty list"); while (current->next != NULL) current = current->next; return current->data; } template T* tlist::get(const int ndx) const { if (ndx < 0) throw string("Error: Attempt to access non-existent item"); int temp = 0; node* current = head; while (temp < ndx) { if (current == NULL) throw string("Error: Attempt to access non-existent item"); if (ndx == temp) return current->data; current = current->next; temp++; } if (current == NULL) throw string("Error: Attempt to access non-existent item"); return current->data; } template bool tlist::isEmpty() const { return (head == NULL); } template void tlist::add(T* obj) { node* current = head; node* p = new node; assert(p != NULL); p->data = obj; p->next = NULL; if (head == NULL) { head = p; } else { while (current->next != NULL) current = current->next; current->next = p; } } template bool tlist::remove(T* obj) { if (head == NULL) return false; if (head->data->equals(obj)) { head = head->next; return true; } node* prev = head; node* curr = prev->next; while (curr != NULL) { if (curr->data->equals(obj)) { prev->next = curr->next; delete curr; return true; } else { prev = curr; curr = prev->next; } } return false; } #endif