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;
}
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.