montimaj

Stack

Jul 30th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.94 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. struct stack {
  5.      int *a;
  6.      int top;
  7.      int maxSize;
  8. };
  9. void initstack(struct stack *p, int maxSize);
  10. void push(struct stack *p, int item);
  11. void display(struct stack p);
  12. int pop(struct stack *p);
  13. void printMenu();
  14.  
  15. int main() {
  16.      struct stack p;
  17.      int data,ch, data1, m;
  18.      printf("Enter the maximum size of the stack\n");
  19.      scanf("%d",&m);
  20.      initstack(&p,m);
  21.      if(p.a != NULL) {
  22.        do {
  23.          printMenu();
  24.          printf("Enter your choice\n");
  25.          scanf("%d",&ch);
  26.          switch(ch) {
  27.               case 1:
  28.               printf("Enter the element to be pushed\n");
  29.               scanf("%d",&data);
  30.               push(&p, data);
  31.               break;
  32.  
  33.               case 2:
  34.               data1 = pop(&p);
  35.               if(data1 != -1000)
  36.                 printf("The popped element is %d\n",data1);
  37.               break;
  38.  
  39.               case 3:
  40.               printf("The contents of the stack are ");
  41.               display(p);
  42.               printf("\n");
  43.               break;
  44.  
  45.               default:
  46.               free(p.a);
  47.               return 0;
  48.            }
  49.          } while(1);
  50.     }
  51.     return 0;
  52. }
  53.  
  54. void printMenu() {
  55.   printf("Choice 1 : Push\n");
  56.   printf("Choice 2 : Pop\n");
  57.   printf("Choice 3 : Display\n");
  58.   printf("Any other choice : Exit\n");
  59. }
  60.  
  61. void initstack(struct stack *p, int maxSize) {
  62.   p->top = -1;
  63.   p->maxSize = maxSize;
  64.   p->a = malloc(maxSize * sizeof(int));
  65. }
  66.  
  67. void push(struct stack *p, int item) {
  68.   if(p->top < p->maxSize-1) {
  69.     p->a[++p->top] = item;
  70.   } else {
  71.       printf("Stack is full\n");
  72.   }
  73. }
  74.  
  75. void display(struct stack p) {
  76.   int i = 0;
  77.   if(p.top == -1) {
  78.     printf("{}");
  79.   }
  80.   for (; i <= p.top; ++i) {
  81.     printf("%d  ", p.a[i]);
  82.   }
  83. }
  84.  
  85. int pop(struct stack *p) {
  86.     if(p->top == -1) {
  87.       printf("Stack is empty\n");
  88.       return -1000;
  89.     }
  90.     return p->a[p->top--];
  91. }
Add Comment
Please, Sign In to add comment