Advertisement
oopmsolutions

Stack

Oct 31st, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #define _CRT_NO_SECURE_WARNINGS
  2. #define _CRT_SECURE_NO_DEPRECATE
  3. #include<stdio.h>
  4. #define MAX 5
  5.  
  6. typedef struct
  7. {
  8.     int tos;
  9.     int s[MAX];
  10. }stack;
  11.  
  12. void push(stack *t, int ele)
  13. {
  14.     if (t->tos == MAX - 1)
  15.     {
  16.         printf("\nStack Overflow\n");
  17.         return;
  18.     }
  19.     else
  20.     {
  21.         t->tos++;
  22.         t->s[t->tos] = ele;    
  23.     }
  24. }
  25.  
  26. void display(stack *t)
  27. {
  28.     int i;
  29.     if (t->tos == -1)
  30.     {
  31.         printf("\nStack Empty\n");
  32.         return;
  33.     }
  34.     else
  35.     {
  36.         for (i = t->tos; i >= 0; i--)
  37.             printf("\t%d",t->s[i]);
  38.         printf("\n");
  39.     }
  40. }
  41.  
  42. int pop(stack *t)
  43. {
  44.     int x;
  45.     if (t->tos == -1)
  46.     {
  47.         printf("\nStack Underflow\n");
  48.         return -1;
  49.     }
  50.     else
  51.     {  
  52.         x = stacktop(t);
  53.         t->tos--;
  54.         return x;
  55.     }
  56. }
  57.  
  58. int stacktop(stack *t)
  59. {
  60.     return t->s[t->tos];
  61. }
  62.  
  63. void main()
  64. {
  65.     stack s;
  66.     s.tos = -1;
  67.     int ch, ele;
  68.     while (1)
  69.     {
  70.         printf("\nEnter your choice\n1.Push\n2.Pop\n3.Display\n4.Stack Top\n5.Exit\n\n");
  71.         scanf("%d", &ch);
  72.         if (ch == 5)
  73.             break;
  74.         switch (ch)
  75.         {
  76.             case 1:
  77.                 if (s.tos == MAX - 1)
  78.                     printf("\nStack Overflow\n");
  79.                 else
  80.                 {
  81.                     printf("\nEnter the element to be pushed\n");
  82.                     scanf("%d", &ele);
  83.                     push(&s, ele);
  84.                     display(&s);
  85.  
  86.                 }
  87.                 break;
  88.             case 2:
  89.                 if (s.tos == -1)
  90.                     printf("\nStack Underflow\n");
  91.                 else
  92.                     printf("\nThe popped element is %d", pop(&s));
  93.                 break;
  94.             case 3:
  95.                 display(&s);
  96.                 break;
  97.             case 4:
  98.                 if (s.tos == -1)
  99.                     printf("\nStack Empty");
  100.                 else
  101.                     printf("\nElement at the top of the stack is %d", stacktop(&s));
  102.                 break;
  103.             default:
  104.                 printf("\nInvalid Choice.");
  105.         }
  106.        
  107.     }
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement