Traverse Linked list in Reverse order :
In case of singly linked list, it is quit difficult to traverse the linked list in reverse order.
How we traverse a linked list:
Generally, we using first pointer we traverse all linked list element until NULL value is come.
But we want to traverse from the last so it is possible by the recursion.
Useful code:
int rtraverse(struct node *ptr)
{
if(ptr==NULL)
return 0;
rtraverse(ptr->link);
printf("%d ",ptr->data);
}
#include< stdio.h>
#include< conio.h>
#include< alloc.h>
struct node{
struct node *link;
int data;
};
struct node *first=NULL;
int rtraverse(struct node *ptr)
{
if(ptr==NULL)
return 0;
rtraverse(ptr->link);
printf("%d ",ptr->data);
}
int traverse()
{
struct node *ptr;
ptr=first;
while(ptr!=NULL){
printf("%d ",ptr->data);
ptr=ptr->link;
}
}
void main()
{
struct node *cpt,*ptr;
int n,pos;
char ch;
clrscr();
first=(struct node*)malloc(sizeof(struct node));
printf("Enter first element in Linklist\n");
scanf("%d",&first->data);
ptr=first;
do
{
cpt=(struct node*)malloc(sizeof(struct node));
printf("Enter another data\n");
scanf("%d",&cpt->data);
ptr->link=cpt;
ptr=ptr->link;
printf("Continue(y/n) ?");
ch=getch();
}while(ch=='y');
ptr->link=NULL;
printf("Linklist is\n");
traverse();
printf("Linklist in reverse direction\n");
rtraverse(first);
getch();
}
Enter first element in Linked list
2
Enter another data
4
Continue(y/n)?
Enter another data
1
Continue(y/n) ?
Enter another data
9
Continue(y/n) ?
Enter another data
0
Continue(y/n) ?
Linklist is :
2 4 1 9 0
Linked in reverse direction
0 9 1 4 2