The student wants the increment function to change the value of num in main, but
ID: 3559414 • Letter: T
Question
The student wants the increment function to change the value of num in main, but currently their code always prints out the value of 5 for num before and after the call to increment(num). Why doesn't the student's code change the value of num when calling increment(num)? Fix the problem. (You don't need to rewrite the whole code just the corrections. Given the LinkedList class above, write a C++ function to accept an object of type LinkedList as a parameter and add a new object to the end and one to the front of the existing list. You may not make any assumption regarding the size of the list. Prompt user for the information for the 2 new nodes.Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
// Node class
class Node {
string data;
Node* next;
public:
Node() {};
void SetData(string aData) { data = aData; };
void SetNext(Node* aNext) { next = aNext; };
string Data() { return data; };
Node* Next() { return next; };
};
// List class
class List {
Node *head;
public:
List() { head = NULL; };
void Print();
void Append(string data);
};
/**
* Print the contents of the list
*/
void List::Print() {
// Temp pointer
Node *tmp = head;
// No nodes
if ( tmp == NULL ) {
cout << "EMPTY" << endl;
return;
}
// One node in the list
if ( tmp->Next() == NULL ) {
cout << tmp->Data();
cout << " --> ";
cout << "NULL" << endl;
}
else {
// Parse and print the list
do {
cout << tmp->Data();
cout << " --> ";
tmp = tmp->Next();
}
while ( tmp != NULL );
cout << "NULL" << endl;
}
}
/**
* Append a node to the linked list
*/
void List::Append(string data) {
// Create a new node
Node* newNode = new Node();
newNode->SetData(data);
newNode->SetNext(NULL);
// Create a temp pointer
Node *tmp = head;
if ( tmp != NULL ) {
// Nodes already present in the list
// Parse to end of list
while ( tmp->Next() != NULL ) {
tmp = tmp->Next();
}
// Point the last node to the new node
tmp->SetNext(newNode);
}
else {
// First node in the list
head = newNode;
}
}
int main()
{
// New list
List list;
list.Append("a");
list.Append("b");
list.Append("c");
list.Append("d");
list.Append("e");
list.Print();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.