Question
You will need to expand the capabilities of the Node class by implementing 2 additional methods and revising the addNode method. Add a method to
You will need to expand the capabilities of the Node class by implementing 2 additional methods and revising the addNode method. Add a method to the Node class named pushBack that accepts an integer argument. This method should dynamically create a new Node object that is initialized with the provided integer. It should then use the addNode method to link the new Node to the current Node. The addNode method should be made private instead of public. But wait a minute, there is a problem. What happens if someone calls the addNode method, but the next pointer is not NULL? In this case you will need to make sure the next pointer is NULL before linking the two nodes together. For this assignment, the adding of a new Node onto the chain should only be allowed to occur at the end of the chain. To accomplish this, update the addNode method to be recursive. The method should recurse until NULL is reached before linking the new Node. Note that in this example of recursion, when the addNode method calls the addNode method, it is actually calling the method on a different object. Note that it is possible to add a Node to the middle of the chain, but this will require some additional code to make it work and the pointer manipulations involved are not for the faint of heart. Create a public method named printChain that will print the data value for that Node and for every node in the chain thereafter. The values should be printed separated by spaces on one line. From main create a dynamically allocated Node object and then call the pushBack method 10 times to chain some Nodes together. Call the printChain method to print out the chain. You do not need to worry about freeing the memory used by the program.
This is what I have been working on for this question (this is pieced together from other sources on here)
#include
using namespace std;
int main() {
Node *nodeArr[10];
for (int i = 0; i < 10; i++) {
nodeArr[i] = new Node(i + 1);
}
for (int i = 0; i < 9; i++) {
nodeArr[i]->addNode(nodeArr[i + 1]);
}
Node *ptr = nodeArr[0];
cout << "Iterating over chain" << endl;
while (ptr != NULL) {
cout << ptr->data << " ";
ptr = ptr->next;
}
return 0;
}
#include
using namespace std;
class Node { private:
void addNode(Node *nodePtr) {
this->num = nodePtr;
}
public:
int data;
Node *next;
Node(int data) {
this->data = data;
next = NULL;
cout << "Node initialized with data " << data << endl;
}
void pushBack(int num) {
this->next = num;
}
};
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started