Redo these 3 functions so that they use recursion please. 1) void insertAtEnd(No
ID: 3602095 • Letter: R
Question
Redo these 3 functions so that they use recursion please.
1)
void insertAtEnd(NodeType* &head, int value) { //recurse this
NodeType *temp;
temp = new(NodeType);
temp->info = value;
temp->nextPtr = NULL;
if (!head) {
head = temp;
return;
}
else {
NodeType* last = head;
while (last->nextPtr)
last = last->nextPtr;
last->nextPtr = temp;
}
}
2)
void print(NodeType *head)
{
NodeType *temp;
if (head == NULL) {
cout << "The List is Empty" << endl;
return;
}
temp = head;
cout << "Elements of list are: " << endl;
while (temp != NULL)
{
cout << temp->info << "->";
temp = temp->nextPtr;
}
cout << "NULL" << endl;
}
3)
void findAndDelete(NodeType **head, int value)
{
NodeType *prev = NULL;
NodeType *curr = *head;
if (find(*head, value)) {
while (curr) {
if ((curr == *head) && (curr->info == value)) {
*head = curr->nextPtr;
delete(curr);
cout << "Element " << value << " deleted from the list" << endl;
return;
}
if (curr->info == value) {
prev->nextPtr = curr->nextPtr;
delete(curr);
cout << "Element " << value << " deleted from the list" << endl;
return;
}
prev = curr;
curr = curr->nextPtr;
}
delete(curr);
cout << "Element " << value << " deleted from the list" << endl;
return;
}
cout << "value to deleted not found on the list" << endl;
return;
}
Explanation / Answer
Hi,
1. here is the code with comments
void insertAtEnd(NodeType* &head, int value) { //recurse this
NodeType *temp;
temp = new(NodeType);
temp->info = value;
temp->nextPtr = NULL;
if(head == NULL) //base case
head = temp;
else insert(head->next, value);//recursive till the last element
}
2.
void print(NodeType *head)
{
if (head==NULL)// base case for last element
{
cout << "NULL";
return;
}
cout << head->data <<"->"<<endl;//recursively pass the next pointer
print(head->next);
}
To print the "Elements of list" you can use a wrapper function above this function and call the recursion function above
Thumbs up if this was helpful, otherwise let me know in comments
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.