#include #include #include #include "linked_list.h" using namespace std; struct linked_list::list_node { list_node(int init_data = 0, list_node * link = nullptr) { data = init_data; next = link; } int data; list_node * next; }; linked_list::linked_list() { front = nullptr; back = nullptr; count = 0; } void linked_list::add(int data) { if (back == nullptr) { front = new list_node(data); back = front; count = 0; } else { back->next = new list_node(data); back = back->next; } count++; } string linked_list::to_string() const { ostringstream out; out << "["; if (count > 0) { out << front->data; list_node * current = front->next; while (current != nullptr) { out << ", " << current->data; current = current->next; } } out << "]"; return out.str(); } bool linked_list::contains(int value) const { list_node * current = front; while (current != nullptr) { if (current->data == value) { return true; } current = current->next; } return false; } int linked_list::size() const { return count; } void linked_list::clear() { delete_nodes(front); front = nullptr; back = nullptr; count = 0; } linked_list::linked_list(const linked_list & rhs) { copy_from(rhs.front); count = rhs.count; } linked_list::~linked_list() { delete_nodes(front); } linked_list & linked_list::operator=(const linked_list & rhs) { if (this != &rhs) { delete_nodes(front); copy_from(rhs.front); count = rhs.count; } return *this; } const int & linked_list::operator[](int index) const { return node_at(index)->data; } int & linked_list::operator[](int index) { return node_at(index)->data; } void linked_list::delete_nodes(list_node * current) { while (current != nullptr) { list_node * temp = current; current = current->next; delete temp; } } void linked_list::copy_from(list_node * other) { if (other == nullptr) { front = nullptr; back = nullptr; } else { front = new list_node(other->data); list_node * current1 = front; list_node * current2 = other->next; while (current2 != nullptr) { current1->next = new list_node(current2->data); current2 = current2->next; current1 = current1->next; } back = current1; } } linked_list::list_node * linked_list::node_at(int index) const { list_node * current = front; while (index > 0) { current = current->next; index--; } return current; } void print(const linked_list & list) { cout << "["; if (list.size() > 0) { cout << list[0]; for (int i = 1; i < list.size(); i++) { cout << ", " << list[i]; } } cout << "]"; }