#include "AppendableList.h" #include #include using namespace std; // PRE: // POST: default constructor AppendableList::AppendableList() { head = NULL; tail = NULL; size = 0; } // PRE: // PARAM: list to be copied // POST: copy constructor AppendableList::AppendableList(const AppendableList & list) { copyList(list); } // PRE: // PARAM: list to be assigned // POST: overloaded assignment operator AppendableList & AppendableList::operator=(const AppendableList & list) { if(this != &list){ // checks for self assignment removeAll(); copyList(list); } return *this; } // PRE: // POST: overloaded [] operator, returns reference to int int & AppendableList::operator[](int i) { Node* temp = head; for(int j = 0; j < i; j++){ temp = temp->next; } return temp->data; } // PRE: // POST: deallocates memory associated with list AppendableList::~AppendableList() { removeAll(); } // PRE: // POST: returns 1 if list is empty, 0 otherwise int AppendableList::empty() { return head == NULL; } // POST: returns number of values stored in list int AppendableList::length() { return size; } // PRE: // PARAM: value = value to be appended // POST: adds a new element to the tail of list void AppendableList::append(int value) { // Build the node to be appended Node* newNode = new Node(value); // List is empty if(tail == NULL){ head = tail = newNode; }else{ // List not empty tail->next = newNode; tail = newNode; } size++; } // PRE: i < AL->size // PARAM: i = index of data to be returned // POST: returns the date in the ith node in the list int AppendableList::get(int i) { Node* temp = head; for(int j = 0; j < i; j++){ temp = temp->next; } return temp->data; } // PRE: i < AL->size // PARAM: i = index of data to be set // value = new value // POST: changes the data in the ith node of the list to value void AppendableList::set(int i, int value) { Node* temp = head; for(int j = 0; j < i; j++){ temp = temp->next; } temp->data = value; } // PRE: // POST: prints list elements from head to tail void AppendableList::print() { cout << "{ "; printHelper(head); cout << "}" << endl; } // PRE: // POST: removes all nodes from list void AppendableList::removeAll() { Node* current = head; while(head != NULL){ head = head->next; delete current; current = head; } head = tail = NULL; } // PRE: // PARAM: current = node to be printed // POST: prints list elements from current to tail void AppendableList::printHelper(Node* current) { if(current != NULL){ cout << current->data << " "; printHelper(current->next); } } // PARAM: list to be copied // POST: makes a deep copy of list void AppendableList::copyList(const AppendableList & list) { if(list.head != NULL){ // Copy front Node* original = list.head; head = new Node(original->data); tail = head; original = original->next; Node* temp = head; // Copy rest of list while(original != NULL){ temp->next = new Node(original->data); original = original->next; temp = temp->next; tail = temp; } } size = list.size; }