/* linkedList.cpp CIS 250 3/15/10 David Klick Linked list specification */ #include "linkedList.h" #include #include #include using std::cout; using std::endl; using std::string; linkedList::linkedList() { count = 0; head = NULL; } linkedList::~linkedList() { while (head != NULL) { node* hold = head->next; delete head; head = hold; count--; } } int linkedList::length() const { return count; } void linkedList::print() const { node* pos = head; while (pos != NULL) { cout << pos->data << " "; pos = pos->next; } cout << endl; } bool linkedList::search(int val) const { bool found = false; node* pos = head; while (pos != NULL) { if (pos->data == val) { found = true; break; } pos = pos->next; } return found; } int linkedList::front() const { if (head == NULL) throw string("Error: Accessing empty list"); return head->data; } int linkedList::back() const { if (head == NULL) throw string("Error: Accessing empty list"); node* pos = head; while (pos->next != NULL) pos = pos->next; return pos->data; } bool linkedList::isEmpty() const { return head == NULL; } void linkedList::addFirst(int val) { node* elephant = new node; assert (elephant != NULL); elephant->data = val; elephant->next = head; head = elephant; count++; } void linkedList::addLast(int val) { node* elephant = new node; assert (elephant != NULL); elephant->data = val; elephant->next = NULL; if (head == NULL) { head = elephant; } else { node* pos = head; while (pos->next != NULL) pos = pos->next; pos->next = elephant; } count++; } void linkedList::add(int val) { addLast(val); } bool linkedList::remove(int val) { if (head == NULL) return false; if (head->data == val) { node *temp = head; head = head->next; delete temp; count--; return true; } node* prev = head; node* curr = prev->next; while (curr != NULL) { if (curr->data == val) { prev->next = curr->next; delete curr; count--; return true; } else { prev = curr; curr = curr->next; } } return false; } ostream& operator<<(ostream& out, const linkedList &lst) { linkedList::node* current = lst.head; while (current != NULL) { out << current->data << " "; current = current->next; } return out; }