Question: Write a program to reverse a linked list using recursion.
Solution:
#include<stdio.h>
#include<stdlib.h>
int k=0;
void create();
void display();
void prereverse();
struct node{
int val;
struct node *next;
};
int *p,n,c,r,c=1;
void reverse();
struct node *curr,*tail,*head;
struct node *prevNode, *curNode;
int main(){
int n,b;
while(c!=0){
printf("============= Menu ===========\n");
printf("PRESS 0 FOR EXITS THE SYSTEM\n");
printf("PRESS 1 FOR CREATE A LINK LIST\n");
printf("PRESS 2 FOR PRINT THE LINK LIST\n");
printf("PRESS 3 FOR REVERSE THE LINK LIST\n");
printf("\nPLEASE ENTER YOUR CHOICE\n");
scanf("%d",&b);
if(b==0){
printf("=======YOUR SYSTEM IS EXIT PLLEASE VISIT ANOTHER TIME THANK YOU========\n");
exit(0);
}
else if(b==1){
printf("\nENTER THE NUMBER OF VALUES\n");
scanf("%d",&n);
int *p;
p=(int*)malloc(n*sizeof(int));
if(p==NULL){
printf("\nYOUR MEMORY ARE NOT ALLOCATED\n");
}
else if(p!=NULL){
printf("CONGRATULATION YOUR MEMORY SUCESSFULLY ALOCATED\n");
printf("ENTER THE REQUIRE ELEMENTS\n");
for(int i=0;i<n;i++){
scanf("%d",&p[i]);
}
create(p,n);
}
}
else if(b==2){
display();
}
else if(b==3){
reverse();
}
}
return 0;
}
void create(int *p,int n){
for(int i=0;i<n;i++){
curr =(struct node*)malloc(sizeof(struct node));
curr-> val =*(p+i);
curr->next = NULL;
if (head == NULL)
{
head = curr;
tail = curr;
}
else {
tail->next = curr;
tail = curr;
}
}
}
void display()
{
curr = head;
printf("\n");
while(curr!= NULL)
{
printf(" %d---> ", curr->val);
curr = curr->next;
}
}
void prereverse(){
prevNode=head;
curNode= head->next;
head=head->next;
prevNode->next=NULL;
}
void reverse(){
if(k==0){
prereverse();
k++;
}
if(head!=NULL){
head = head->next;
curNode->next = prevNode;
prevNode = curNode;
curNode = head;
reverse();
}
printf(" HERE THE LINK LIST IS SUCESSFULLY REVERSED \n");
head = prevNode;
}