Question: In C++, use the code below and then do the following: - Modify the Node class to include a pointer to a number rather than
In C++, use the code below and then do the following:
- Modify the Node class to include a pointer to a number rather than the number itself.
- Modify the constructor to allocate the memory for the pointer to the number
- Modify the print method to print the pointer to the number rather than the number itself.
- Add a destructor
- Write a method named "insert" to insert a number at the BEGINNING of the list
- In the main, demonstrate that the code works by:
Creating nodeObj4 with a value 333
Creating nodeObj5 with a value 111
Insert nodeObj4 at the beginning
Insert nodeObj5 at the beginning
CODE:
#includeusing namespace std; class Node { public: Node(int ); void InsertAfter(Node* nodePtr); void InsertAtEnd(); Node* GetNext(); void PrintNodeData(); private: int Num; Node* next; }; //Constructor Node::Node(int dataInit) { this->Num = dataInit; this->next= 0; return; } // Insert node after this node. void Node::InsertAfter(Node* nodeLoc) { Node* tmpNext = 0; tmpNext = this->next; // Remember next this->next= nodeLoc; // this -- node -- ? nodeLoc->next= tmpNext; // this -- node -- next return; } // Insert at the end void Node::InsertAtEnd() { Node* curr = 0; curr=this; if (curr== 0){ cout << "error - there is no list created"<< endl; return; } while (curr->next !=0 ) curr = curr->next; cout<< "I found the last data element: " << curr->Num << endl; return; } // Print Num void Node::PrintNodeData() { cout << this->Num << endl; return; } // Grab location pointed by next Node* Node::GetNext() { return this->next; } int main() { Node* headObj = 0; // Create intNode objects Node* nodeObj1 = 0; Node* nodeObj2 = 0; Node* nodeObj3 = 0; Node* currObj = 0; //Beginning of list of Node headObj = new Node(-1); // Insert nodes nodeObj1 = new Node(555); nodeObj2 = new Node(999); nodeObj3 = new Node(777); headObj->InsertAfter(nodeObj1); nodeObj1->InsertAfter(nodeObj2); nodeObj2->InsertAfter(nodeObj3); // Print linked list currObj = headObj; while (currObj != 0) { currObj->PrintNodeData(); currObj = currObj->GetNext(); } headObj->InsertAtEnd(); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
