Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, I need to convert this class code to template class code. I already have the

ID: 3566058 • Letter: H

Question

Hi, I need to convert this class code to template class code. I already have the main code

#include <iostream>

using namespace std;

class List
{
struct Node
{
int data;
Node * next;
};

Node * head;

public:
List()
{
head = NULL;
}

~List()
{ // delete the list
while(head != NULL)
{
Node * n = head->next;
delete head;
head = n;
}
}

void add(int value)
{
Node * n = new Node;
n->data = value;
n->next = head;
head = n;
}

void show()
{
while(head !=NULL)
{
Node * n = head->next;
cout<< head->data <<", ";head = n;
}
cout << endl;
}
};

Explanation / Answer

#include <iostream>

using namespace std;

template <class T>
class List{
struct Node{
T data;
Node * next;
};
Node *head;

public:
List(){
head = NULL;
}

~List(){ // delete the list
while(head != NULL){
Node * n = head->next;
delete head;
head = n;
}
}

void add(T value){
Node * n = new Node;
n->data = value;
n->next = head;
head = n;
}

void show(){
while(head !=NULL){
Node * n = head->next;
cout<< head->data <<", ";head = n;
}
cout << endl;
}
};

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote