C code for reversing linked list recursively


//linked list implementation in C
//display, reverse recursively
//recursive function to reverse a list
#include<stdio.h>
#include<malloc.h>
void insert(int d);
void display();

struct node
{
int data;
struct node *next;
};
struct node *start;

int main()
{
start=NULL;//starting with empty list
insert(10);//first element
insert(15);
insert(11);
insert(99);//last element

struct node *current1=(struct node*)malloc(sizeof(struct node));
current1=start;
printf("\nOriginal List was:\n");
display();
printf("\nRecursively reversed List is:\n");
revRec(current1);

return 0;
}
void insert(int d)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=d;
newnode->next=start;
start=newnode;
}


void display()
{
struct node *ptr=start;
while(ptr!=NULL)
{
printf("ptr=%d and ptr->data=%d \n",ptr,ptr->data);
ptr=ptr->next;
}
}




void revRec(struct node *current1)
{
if(current1==NULL)//here we can not take current1 and initialized with start otherwise always same conditiuon
return;

else
revRec(current1->next);

printf("current1=%d and current1->data=%d \n",current1,current1->data);

}
/*
Original List was:
ptr=160849976 and ptr->data=99
ptr=160849960 and ptr->data=11
ptr=160849944 and ptr->data=15
ptr=160849928 and ptr->data=10

Recursively reversed List is:
current1=160849928 and current1->data=10
current1=160849944 and current1->data=15
current1=160849960 and current1->data=11
current1=160849976 and current1->data=99
*/
/*
In stack:
10 was stored in lowest address then 15 then 11 and last 99 in higgest addres
when printrd in revRec
printed last entered element ie 99 then 11 then 15 then 10 last
*/

No comments:

Post a Comment