// first version of a linked list class with add, size, and to_string and it // passes valgrind #include #include #include using namespace std; struct list_node { list_node(int init_data = 0, list_node * link = nullptr) { data = init_data; next = link; } int data; list_node * next; }; class linked_list { public: linked_list() { front = nullptr; back = nullptr; count = 0; } ~linked_list() { delete_nodes(front); } void delete_nodes(list_node * current) { while (current != nullptr) { list_node * temp = current; current = current->next; delete temp; } } int size() const { return count; } void add(int value) { if (count == 0) { front = new list_node(value); back = front; count = 1; } else { back->next = new list_node(value); count++; back = back->next; } } string 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(); } private: list_node * front; list_node * back; int count; }; int main() { linked_list list; list.add(3); list.add(5); list.add(2); list.add(17); cout << "list size = " << list.size() << endl; cout << list.to_string() << endl; cout << endl; linked_list list1; for (int n : {3, 18, 12, 7, 13, 20, 0, 7}) { cout << "list1 = " << list1.to_string() << ", adding " << n << endl; list1.add(n); } cout << "final list1 = " << list1.to_string() << endl; cout << "final list1 size = " << list1.size() << endl; cout << endl; return 0; }