Here we traversing the singly-link list in reverse order without saving the contents in another strucutre
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct link
{
int data;
struct link *next;
};
void add(struct link **p,int d)
{struct link *r,*q;
q=*p;
if(*p==NULL)
{
r=(struct link *)malloc(sizeof(struct link));
r->data=d;
r->next=NULL;
*p=r;
}
else
{
while(q->next!=NULL)
{q=q->next;
}
r=(struct link *)malloc(sizeof(struct link));
r->data=d;
r->next=NULL;
q->next=r;
}
}
void display(struct link **p)
{
struct link *q=*p;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->next;
}
}
void reversetraverse(struct link *p)//using recursion we traversing
{
struct link *q=p;
if(q->next==NULL)
{
printf("%d\n",q->data);
return;
}
reversetraverse(q->next);
printf("%d\n",q->data);
}
main()
{
struct link *p;
p=NULL;
add(&p,5);
add(&p,5);
add(&p,6);
display(&p);
reversetraverse(p);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct link
{
int data;
struct link *next;
};
void add(struct link **p,int d)
{struct link *r,*q;
q=*p;
if(*p==NULL)
{
r=(struct link *)malloc(sizeof(struct link));
r->data=d;
r->next=NULL;
*p=r;
}
else
{
while(q->next!=NULL)
{q=q->next;
}
r=(struct link *)malloc(sizeof(struct link));
r->data=d;
r->next=NULL;
q->next=r;
}
}
void display(struct link **p)
{
struct link *q=*p;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->next;
}
}
void reversetraverse(struct link *p)//using recursion we traversing
{
struct link *q=p;
if(q->next==NULL)
{
printf("%d\n",q->data);
return;
}
reversetraverse(q->next);
printf("%d\n",q->data);
}
main()
{
struct link *p;
p=NULL;
add(&p,5);
add(&p,5);
add(&p,6);
display(&p);
reversetraverse(p);
getch();
}
No comments:
Post a Comment