#include #include #include "linkedlist_bigthree.h" #include "node.h" // Constructs an empty linked list LinkedList::LinkedList() { head = NULL; } // Destructs (frees memory) the linked list LinkedList::~LinkedList() { clear(); } // Constructs a new linked list given an existing list LinkedList::LinkedList(const LinkedList &rhs) { head = NULL; if(rhs.head != NULL) { head = new Node(rhs.head->value(), NULL); Node* rhs_curr = rhs.head->next(); Node* this_curr = head; while(rhs_curr != NULL) { this_curr->setNext(new Node(rhs_curr->value(), NULL)); this_curr = this_curr->next(); rhs_curr = rhs_curr->next(); } } } // Does a deep copy of one list to another LinkedList & LinkedList::operator=(const LinkedList& rhs) { if(this != &rhs) { clear(); if(rhs.head != NULL) { head = new Node(rhs.head->value(), NULL); Node* rhs_curr = rhs.head->next(); Node* this_curr = head; while(rhs_curr != NULL) { this_curr->setNext(new Node(rhs_curr->value(), NULL)); this_curr = this_curr->next(); rhs_curr = rhs_curr->next(); } } } return *this; } // Adds a node to the head of the list void LinkedList::addFirst(int value) { head = new Node(value, head); } // Removes node from head of list int LinkedList::removeFirst() { assert(head != NULL); int return_val = head->value(); Node* old_head = head; head = head->next(); // advance the head pointer delete old_head; // free the memory for the old head return return_val; } // Return integer value of head node int LinkedList::getFirst() const { return head->value(); } // Checks if list contains value bool LinkedList::contains(int value) const { Node* finger = head; while( finger != NULL && finger->value() != value ){ finger = finger->next(); } return finger != NULL; } // Clears the linked list void LinkedList::clear() { if(!isEmpty()) { Node* prev = NULL; Node* curr = head; while(curr->next() != NULL) { prev = curr; curr = curr->next(); delete prev; } delete curr; head = NULL; } } // Sets the node at position index to value void LinkedList::set(int index, int value) { Node* finger = head; for( int i = 0; i < index && head != NULL; i++ ){ finger = finger->next(); } if( finger != NULL ){ finger->setValue(value); } } // Checks if list is empty bool LinkedList::isEmpty() { return head == NULL; }