document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4.  
  5. #define MAX_STACK_SIZE      100
  6. typedef struct{
  7.   int key;
  8. }element;
  9.  
  10. element stack[MAX_STACK_SIZE];
  11. int top = -1;
  12.  
  13. bool isEmpty();
  14. bool isFull();
  15. void push(element item);
  16. element pop();
  17. void stackFull();
  18. void stackEmpty();
  19. void stackDisplay();
  20.  
  21. int main(void)
  22. {
  23.   int selection;
  24.   int tmp;
  25.   int i;
  26.   element tmpItem;
  27.  
  28.   printf("stack program test\\n");
  29.   while(1){
  30.     printf("\\n- menu - \\n");
  31.     printf("1. push\\n");
  32.     printf("2. pop\\n");
  33.     printf("3. display\\n");
  34.     printf("4. exit\\n");
  35.     printf("Select the menu: ");
  36.     scanf("%d", &selection);
  37.  
  38.     switch(selection){
  39.       case 1:
  40.         printf("Enter the key: ");
  41.         scanf("%d", &tmp);
  42.         tmpItem.key = tmp;
  43.         push(tmpItem);
  44.         break;
  45.  
  46.       case 2:
  47.         tmpItem = pop();
  48.         printf("Pop the item: %d\\n", tmpItem.key);
  49.         break;
  50.  
  51.       case 3:
  52.         stackDisplay();
  53.         break;
  54.  
  55.       case 4:
  56.         return 1;
  57.  
  58.       default:
  59.         printf("you must enter the number listed on menu\\n");
  60.         break;
  61.     }
  62.   }
  63.   return 0;
  64. }
  65.  
  66. bool isEmpty()
  67. {
  68.   return top < 0;
  69. }
  70.  
  71. bool isFull()
  72. {
  73.   return top >= MAX_STACK_SIZE - 1;
  74. }
  75.  
  76. void push(element item)
  77. {
  78.   if(top >= MAX_STACK_SIZE -1){
  79.     stackFull();
  80.   }
  81.   stack[++top] = item;
  82. }
  83.  
  84. element pop()
  85. {
  86.   if(top == -1)
  87.     stackEmpty();
  88.   return stack[top--];
  89. }
  90.  
  91. void stackFull()
  92. {
  93.   fprintf(stderr, "Stack is full, cannot add element\\n");
  94.   exit(EXIT_FAILURE);
  95. }
  96.  
  97. void stackEmpty()
  98. {
  99.   fprintf(stderr, "Stack is empty, cannot pop element\\n");
  100.   exit(EXIT_FAILURE);
  101. }
  102.  
  103. void stackDisplay()
  104. {
  105.   int i;
  106.   if(isEmpty()) stackEmpty();
  107.   printf("\\nstack key list\\n");
  108.   for(i = 0; i < top + 1; i++){
  109.     printf("stack[%d] : %d\\n", i, stack[i].key);
  110.   }
  111. }
');