#ifndef LINKEDLIST_CPP #define LINKEDLIST_CPP #include "node.cpp" #include #include template class LinkedList{ public: LinkedList(){ head = NULL; } ~LinkedList(){ clear(); } LinkedList(const LinkedList& rhs){ *this = rhs; // why reinvent the wheel... just use the = operator :) } const LinkedList& operator=(const LinkedList& rhs){ if( this != &rhs ){ clear(); // release the memory of the current linked list if( rhs.head == NULL ){ head = NULL; }else{ head = new Node(rhs.head->value()); Node* finger = rhs.head->next(); Node* current = head; while( finger != NULL ){ current->setNext(new Node(finger->value())); current = current->next(); finger = finger->next(); } } } return *this; } T& operator[](unsigned int index){ Node* finger = head; for( int i = 0; i < index && head != NULL; i++ ){ finger = finger->next(); } assert(finger != NULL); return finger->modValue(); } void addFirst(T value){ head = new Node(value, head); } T removeFirst(){ assert(head != NULL); T returnMe = head->value(); Node* oldHead = head; head = head->next(); delete oldHead; return returnMe; } T getFirst() const{ return head->value(); } bool contains(T value) const{ Node* finger = head; while( finger != NULL && finger->value() != value ){ finger = finger->next(); } return finger != NULL; } void set(int index, T value){ Node* finger = head; for( int i = 0; i < index && head != NULL; i++ ){ finger = finger->next(); } if( finger != NULL ){ finger->setValue(value); } } void clear(){ while( !isEmpty() ){ removeFirst(); } } bool isEmpty(){ return head == NULL; } private: Node* head; }; #endif