Question
In file "LinkedList.cpp", you are given a layout of singly linked list in C++, and a main function (for testing) as well. You are to complete the code and get it work correctly. To be specific, you need to complete the definition of the following functions: a. LinkedList::LinkedList(LinkedList& ll) b. LinkedList& LinkedList::operator=(LinkedList& ll) c. Node* LinkedList::insert_after_current(int value) d. void LinkedList::delete_after_current() #include #include "std_lib_facilities.h" using namespace std; struct Node { int data; Node* next; Node(int d=0, Node* n=0) : data(d), next(n) {} }; class LinkedList { private: Node* head; Node* curr; public: LinkedList() : head(0), curr(0) {} LinkedList(LinkedList& ll); LinkedList& operator=(LinkedList& ll); ~LinkedList(); Node* insert_after_current(int value); void delete_after_current(); void display_list(); void operator++() { curr = curr->next; } void front() { curr = head; } bool is_curr_nonnull() const { return curr != 0; } }; LinkedList::LinkedList(LinkedList& ll) { // Please add codes here } LinkedList& LinkedList::operator=(LinkedList& ll) { if (this == &ll) return *this; Node *p, *node = head; while (node != 0) { p = node; node = node->next; delete p; } // Please add codes here return *this; } LinkedList::~LinkedList() { Node *p, *node = head; while (node != 0) { p = node; node = node->next; delete p; } } Node* LinkedList::insert_after_current(int value) { Node *newnode = new Node(value); if (curr == 0) { if (head != 0) error("Invalid current pointer"); else head = curr = newnode; } else { // Please add codes here } return curr; } void LinkedList::delete_after_current(){ if (curr == 0) { if (head != 0) error("Invalid current pointer"); } else { // Please add codes here } } void LinkedList::display_list() { Node *node = head; while(node != 0) { cout << node->data << " "; node = node->next; } cout << ' '; } int main(){ LinkedList L1; L1.insert_after_current(10); L1.insert_after_current(20); L1.insert_after_current(30); L1.insert_after_current(40); L1.display_list(); L1.front(); L1.delete_after_current(); cout << "list L1: "; L1.display_list(); LinkedList L2(L1); cout << "list L2: "; L2.display_list(); LinkedList L3; cout << "list L3: "; L3.insert_after_current(40); L3.display_list(); L3 = L2; L3.display_list(); return 0; }
Explanation / Answer
/*--- linktester.cpp -------------------------------------------------- A program for testing class LinkedList. Written by: Larry R. Nyhoff Written for: Lab Manual for ADTs, Data Structures, and Problem Solving with C++, 2E Lab #5.1 and Projects 5.1 ---------------------------------------------------------------------*/ #include using namespace std; #include "LinkedList.h" /*---- PART 6 ---- TEST COPY CONSTRUCTOR template // f() is a function template with a void f(LinkedList aList) // LinkedList value parameter { // to test the copy constructor for (int i = 1; i < 5; i++) { aList.insert(i, 100*i); // insert into the copy cout