In the class Singh LinkedList, write a recursive (instance) method that returns
ID: 3687617 • Letter: I
Question
In the class Singh LinkedList, write a recursive (instance) method that returns a new linked list consisting of the first n elements of this list. This instance must remain unchanged. The method public LinkedList take( int n ) must be implemented following the technique presented in class for implementing recursive methods inside the class, i.e. where a recursive method is made of a public nd a private recursive part. The public method initiates the first call to the recursive method. You have to provide a test program that is as exaustif as possible.Explanation / Answer
Recursive Method (Singly Linked list):
program:
// A simple and tail recursive C++ program to reverse
// a linked list
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
void reverseUtil(node *curr, node *prev, node **head);
// This function mainly calls reverseUtil()
// with prev as NULL
void reverse(node **head)
{
if (!head)
return;
reverseUtil(*head, NULL, head);
}
// A simple and tail recursive function to reverse
// a linked list. prev is passed as NULL initially.
void reverseUtil(node *curr, node *prev, node **head)
{
/* If last node mark it head*/
if (!curr->next)
{
*head = curr;
/* Update next to prev node */
curr->next = prev;
return;
}
/* Save curr->next node for recursive call */
node *next = curr->next;
/* and update next ..*/
curr->next = prev;
reverseUtil(next, curr, head);
}
// A utility function to create a new node
node *newNode(int key)
{
node *temp = new node;
temp->data = key;
temp->next = NULL;
return temp;
}
// A utility function to print a linked list
void printlist(node *head)
{
while(head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
// Driver program to test above functions
int main()
{
node *head1 = newNode(1);
head1->next = newNode(2);
head1->next->next = newNode(2);
head1->next->next->next = newNode(4);
head1->next->next->next->next = newNode(5);
head1->next->next->next->next->next = newNode(6);
head1->next->next->next->next->next->next = newNode(7);
head1->next->next->next->next->next->next->next = newNode(8);
cout << "Given linked list ";
printlist(head1);
reverse(&head1);
cout << " Reversed linked list ";
printlist(head1);
return 0;
}
please run on IDE
Program :2 concepts of Returning Value
//length= count(<address of node 1>)