C Program to implement a Stack..

#include<stdio.h>
#define maxi 5

struct stack  // Structure of a stack...
{
int a[maxi];
int top;
};

int flag; // Temporary variable to handle the error condition in pop,peep function...

void push(struct stack *p,int x);
int pop(struct stack *p);
int peep(struct stack s);
void display(struct stack s);

void main()
{
 struct stack a;
 a.top=-1;
 printf("Choice: 1)Insertion 2)Deletion 3)Topmost Element  4)Display 5)Exit");
 int ch,breakcondition=0; // Temporary variable to exit the menu driven program...
 while(1){
 printf("\nEnter your choice..");
 scanf("%d",&ch);
 switch(ch)
 {
  case 1:{int temp;
          printf("\nEnter the element to be inserted..");
          scanf("%d",&temp);
          push(&a,temp);
          break;
         }
  case 2:{
          flag=0;
          int temp=pop(&a);
          if(flag==0)
            printf("\nThe element which is deleted is ..%d",temp);
          break;
         }
  case 3:{
          flag=0;
          int temp=peep(a);
          if(flag==0)
            printf("\nThe Topmost element of the stack is ..%d",temp);
          break;
         }
  case 4:{
          display(a);
          break;
         }
  case 5:{
          breakcondition=1;
          break;
         }
  default:printf("\nPlease enter a valid choice..");
 }
 if(breakcondition==1)
  break;
}
}

void push(struct stack *p,int x)
{
 if(p->top==maxi-1){  // Corner Case to handle if the stack is full...
 printf("\nStack Overflow..");
 return;
 }
 p->a[++p->top]=x;
}

int pop(struct stack *p)
{
 if(p->top!=-1){
  return p->a[p->top--];
}
else{         // Corner Case to handle if the stack is empty...
  printf("\nThe Stack is empty..");
  flag=1;
  return -1;
}
}
int peep(struct stack s)
{
 if(s.top!=-1){
     return s.a[s.top];
 }
 else{       // Corner Case to handle if the stack is empty...
  printf("\nThe Stack is empty..");
  flag=1;
  return -1;
 }
}

void display(struct stack s)
{
   if(s.top==-1){    // Corner Case to handle if the stack is empty...
   printf("\nThe Stack is empty..");
   return;
  }
   while(s.top!=-1){   // Deleting the nodes of the local stack( copy of the original ) and displaying them...
   printf("%d\n",pop(&s));
  }
}

No comments:

Post a comment