In: Computer Science
Write a recursive algorithm replace (start) to replace the value of each element of A with that of the next element in A. A is a singly linked list.
The solution of the above problem is below:
The screenshot of the code is below:
The output screen:
code--
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node*next;
};
void replace(struct node*head)
{
if(head->next==NULL)
{ cout<<head->data;
return;
}
else
{
cout<<head->next->data<< " ";
replace(head->next);
}
}
int main()
{
struct node*p,*head=NULL,*prev;
int i,n;
cout<<"Enter size of likned list";
cin>>n;
int s;
cout<<"Enter value in linked list\n";
for(i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
cin>>s;
p->data=s;
p->next=NULL;
if(head==NULL)
{
head=p;
}
else
{
prev->next=p;
}
prev=p;
}
cout<<"values after replacing of the linked list
is:\n";
replace(head);
}
please upvote in case of any query comment me.