Saturday, 4 March 2017

C program to implement stack using linklist.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct stack
{
int info;
struct stack *next;
}s;
s *top=NULL;
void push(s *,int);
int pop(s *);
void display(s *);
main()
{
int item,choice;
while(1)
{
printf("\n    ***********\n    1.push\n    2.pop\n    3.display\n    4.exit\n    Enter your choice : ");
   scanf("%d",&choice);
switch(choice)
{
case 1:
  printf("enter item to be push :");
  scanf("%d",&item);
  push(top,item);
  break;
case 2:
      item=pop(top);
  printf("popped item is : %d",item);
  break;
case 3:
      display(top);
  break;
case 4:
      exit(1);
  break;
default:
      printf("please enter your choice again");        
}
}
getch();
}
void push(s *p,int item)
{
  s *tmp;
  tmp=(s *)malloc(sizeof(s));
  tmp->info=item;
  tmp->next=top;
  top=tmp;
}
int pop(s *p)
{

int y;
s *tmp;
if(p==NULL)
{
printf("stack is empty");
exit(1);
}
else
{
tmp=top;
top=tmp->next;
y=tmp->info;
free(tmp);
return y;}
}
void display(s *p)
{
s *ptr;
ptr=top;
if(ptr==NULL)
{
printf("stack is empty");
exit(1);
}
else
{

printf("stack is \n");
while(ptr->next!=NULL)
{
printf("|  %d  |\n",ptr->info);
ptr=ptr->next;
}
printf("|  %d  |\n",ptr->info);
}}

No comments:

Post a Comment