Wednesday 7 August 2013

stack program

Description:


In this program we have to implement the stack operation by using the pointers. Here they stack operation are push and pop. Push operation is used to insert the elements into a stack and pop operation is used to remove the elements in to a stack.


#include<stdio.h>
#include<conio.h>
//typedef struct stack
struct stack_tag
{
 int *s;
 int top,size;
};
typedef struct stack_tag stack;
stack init();
void push();
int pop();
void display(stack a);
void menu()
{
 printf("1. insertion\n");
 printf("2. deletion\n");
 printf("3.display stack\n");
 printf("4.exit\n");
}
stack init()
{
 stack a;
 printf("enter size of the stack\n");
 scanf("%d",&a.size);
 a.top=-1;
 a.s=(int*)malloc(a.size*sizeof(int));
 return(a);
}
//b=init();
//push()
void push(stack *p,int x)
{
 if(p->top==p->size-1)
 {
  printf("stack is full, insertion is not possible\n");
 }
 else
 {
  p->top++;
  p->s[p->top]=x;
 }
}
//pop()
int pop(stack *p)
{
 int x;
 if(p->top==-1)//is stack empty?
  return(-1);
 else{
  x=p->s[p->top];//store top most value in x
  p->top--;
  return(x);
 }
}
//x=pop(&a);
void display(stack a)
{
 int i;
 if(a.top==-1)
 {
  printf("stack is empty\n");
  }
 else
 {
  printf("stack is as follows\n");
  for(i=a.top;i>=0;i--)//display values in the stack in reverse order
  { //since stak is LIFO
  printf("%d\n",a.s[i]);
  }
 }//end of else
}
int topmost(stack a)
{
 if(a.top==-1)
  return(-1);
 else
  return(a.s[a.top]);
}
//x=topmost(a);
void main()
{
 stack a;
 int ch,x;
 clrscr();
 a=init();//initialize members of tht structures s,top,size
 clrscr();
 printf("enter your choice\n");
 scanf("%d",&ch);
 while(ch<5)//execute loop until uses,entered choice is 5
 {
  switch(ch)
  {
   case 1:{
       printf("enter value to be inserted\n");
       scanf("%d",&x);
       break;
       }
   case 2:{
       x=pop(&a);//delete top most value in the stack
       if(x==-1)
printf("stack is empty, del not posible\n");
       else
printf("deleted value is %d\n",x);
       break;
      }
   case 3:{
      display(a);//disp value in the stack in rever order
      break;
      }
   case 4: {
x=topmost(a);
if(x==-1)
printf("stack is empty\n");
else
printf("top most value is %d\n",x);
break;
}
   }//switch
  menu();
  printf("enter ur choice\n");
  scanf("%d",&ch);
 }//while
 getch();
}