Welcome To Uday Satya Blog

13 . STACK LINKED LIST



/* ****************************************************
13.TO PERFORM STACK OPERATNS USIN LINKED LISTS.
   *************************************************** */
#include<*stdio.h>
#include<*conio.h>
#include<*alloc.h>
struct link
{
int info;
struct link*next;
}*start;
void display(struct link*);
struct link*push(struct link*);
struct link*pop(struct link*);
int option();
void display(struct link*rec)
{
while(rec!=NULL)
{
printf("%d\t",rec->info);
rec=rec->next;
}
}
struct link*push(struct link*rec)
{
struct link*new_rec;
printf("\n\n enter the new element : ");
new_rec=(struct link*)malloc(sizeof(struct link));
scanf("%d",&new_rec->info);
new_rec->next=rec;
rec=new_rec;
return(rec);
}
struct link*pop(struct link*rec)
{
struct link*temp;
if(rec==NULL)
{
printf("\n\n stack is empty");
}
else
{
temp=rec->next;
free(rec);
rec=temp;
printf("\n\n after pop operation : ");
display(rec);
}
if(rec==NULL)
{
printf("\n\n stack is empty");
}
return(rec);
}
int option()
{
int ch;
do
{
printf("\n\n 1.push \n 2.pop \n 3.quit");
printf("\n\n enter your choice : ");
scanf("%d",&ch);
if(ch<1||ch>3)
printf("\n incorrect choice");
}while(ch<1||ch>3);
return(ch);
}
void main()
{
struct link*start;
int ch;
clrscr();
start=NULL;
do
{
ch=option();
switch(ch)
{
case 1: start=push(start);
          printf("\n\n after push operation : ");
          display(start);
          break;
case 2: start=pop(start);
          break;
case 3: printf("\n\n end of the program");

}
}
while(ch!=3);
getch();
}

outputs

 1.push
 2.pop
 3.quit

 enter your choice : 1

 enter the new element : 1

 after push operation : 1

 1.push
 2.pop
 3.quit

 enter your choice : 1

 enter the new element : 2

 after push operation : 2       1

 1.push
 2.pop
 3.quit

 enter your choice : 1

 enter the new element : 3

 after push operation : 3       2       1

 1.push
 2.pop
 3.quit

 enter your choice : 2

 after pop operation : 2        1

 1.push
 2.pop
 3.quit

 enter your choice : 2

 after pop operation : 1

 1.push
 2.pop
 3.quit

 enter your choice : 2

 after pop operation :

 stack is empty

 1.push
 2.pop
 3.quit

 enter your choice : 3

 end of the program

0 comments:

Post a Comment