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

convert the program using a template #include <iostream> #include <stdlib.h> #in

ID: 3572166 • Letter: C

Question

convert the program using a template


#include <iostream>

#include <stdlib.h>

#include <ctime>

#define MAX_ITERAIONS 1000000

using namespace std;

struct node {

int data;

node *next;

};

int getRandomNumber(){

return rand() % 100;

}

int main(int argc, const char * argv[]) {

node *startNode = nullptr;

node *current = nullptr;

time_t startTime, endTime;

int num = 0;

  

startTime = time(NULL);

  

for(int i=0;i<MAX_ITERAIONS;i++){

num = getRandomNumber();

if(i == 0){

startNode = new node;

startNode->next = 0;

startNode->data = num;

current = startNode;

}else{

current->next = new node;

current->next->data = num;

current->next->next = 0;

current = current->next;

}

}

for(int i=0;i<MAX_ITERAIONS;i++){

int randomNumber = getRandomNumber();

node *previous;

previous = current = startNode;

while(current->data != randomNumber ){

if(current->next == 0){

break;

}else{

previous = current;

current = current->next;

}

}

if(current->next !=0){

previous->next = current->next;

current = NULL;

}else{

previous->next = 0;

current = NULL;

}

}

endTime = time(NULL);

cout << "Start time: " << startTime << " End time: "<< endTime;

cout << " Time Taken: "<< difftime(endTime, startTime)<<" seconds" << endl;

return 0;

}

Explanation / Answer

Hi, Please find my code.

I have added template argument.

Please let me know in case of any issue.

#include <iostream>
#include <stdlib.h>
#include <ctime>

#define MAX_ITERAIONS 1000000
using namespace std;

template <typename T>
struct node {
T data;
node *next;
};

int getRandomNumber(){
return rand() % 100;
}

int main(int argc, const char * argv[]) {
node<int> *startNode = nullptr;
node<int> *current = nullptr;
time_t startTime, endTime;
int num = 0;
  
startTime = time(NULL);
  
for(int i=0;i<MAX_ITERAIONS;i++){
num = getRandomNumber();
if(i == 0){
startNode = new node<int>;
startNode->next = 0;
startNode->data = num;
current = startNode;
}else{
current->next = new node<int>;
current->next->data = num;
current->next->next = 0;
current = current->next;
}
}

for(int i=0;i<MAX_ITERAIONS;i++){
int randomNumber = getRandomNumber();
node<int> *previous;
previous = current = startNode;
while(current->data != randomNumber ){
if(current->next == 0){
break;
}else{
previous = current;
current = current->next;
}
}
if(current->next !=0){
previous->next = current->next;
current = NULL;
}else{
previous->next = 0;
current = NULL;
}
}
endTime = time(NULL);
cout << "Start time: " << startTime << " End time: "<< endTime;
cout << " Time Taken: "<< difftime(endTime, startTime)<<" seconds" << endl;
return 0;
}