Sunday, June 17, 2012

C Program on reversing linked list using stack


Create a linked list and then convert it into a stack. Again the stack is to be convert into a linked list so that the linked list is reversed.

#include< stdio.h>
#include< stdlib.h>
struct tag
{
int a;
struct tag *next;
};
int i=0;
struct tag *node,*p,*p1;
void create(struct tag *n)
{
char ch;
node=n;
printf("\n Want to create(y/n)");
ch=getche();
while(ch!='n')
{
node->next=(struct tag*)malloc(sizeof(struct tag));
node=node->next;
printf("\n Value");
scanf("%d",&node->a);
printf("\nany more(y/n)");
ch=getche();
}
node->next=NULL;
}
void display(struct tag*n)
{
node=n;
if(node==NULL)
i=0;
else
i=1;
while(node)
{
printf("%4d",node->a);
node=node->next;
}
}
struct tag *push(struct tag *p1,struct tag *p2)
{
p2->next=p1;
return(p2);
}
struct tag *delF(struct tag *n)
{
node=n->next;
n->next=node->next;
return(node);
}
struct tag *pop(struct tag *n)
{
node=n->next;
free(n);
return node;
}
void main()
{
struct tag *n,*link,*stack,*p;
clrscr();
link=NULL;
stack=NULL;
create(link);
printf("\nList is as follows\n");
display(link->next);
do
{
p=delF(link);
stack=push(stack,p);
}while(link->next!=NULL);
printf("\nList is as follows (after converting it into a stack.)");
display(link->next);
if(i==0)
printf("\nNo element in the list.");
printf("\nStack is\n");
display(stack);
n=link;
while(stack!=NULL)
{
n->next=stack;
n=n->next;
stack=pop(stack);
}
printf("\nStack is as follows (after converting it into a linked list.)");
display(stack);
if(i==0)
printf("\nNo element in the stack.");
printf("\nFinal list\n");
display(link->next);
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner