Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #define MAX_STACK_SIZE 100
- typedef struct{
- int key;
- }element;
- element stack[MAX_STACK_SIZE];
- int top = -1;
- bool isEmpty();
- bool isFull();
- void push(element item);
- element pop();
- void stackFull();
- void stackEmpty();
- void stackDisplay();
- int main(void)
- {
- int selection;
- int tmp;
- int i;
- element tmpItem;
- printf("stack program test\n");
- while(1){
- printf("\n- menu - \n");
- printf("1. push\n");
- printf("2. pop\n");
- printf("3. display\n");
- printf("4. exit\n");
- printf("Select the menu: ");
- scanf("%d", &selection);
- switch(selection){
- case 1:
- printf("Enter the key: ");
- scanf("%d", &tmp);
- tmpItem.key = tmp;
- push(tmpItem);
- break;
- case 2:
- tmpItem = pop();
- printf("Pop the item: %d\n", tmpItem.key);
- break;
- case 3:
- stackDisplay();
- break;
- case 4:
- return 1;
- default:
- printf("you must enter the number listed on menu\n");
- break;
- }
- }
- return 0;
- }
- bool isEmpty()
- {
- return top < 0;
- }
- bool isFull()
- {
- return top >= MAX_STACK_SIZE - 1;
- }
- void push(element item)
- {
- if(top >= MAX_STACK_SIZE -1){
- stackFull();
- }
- stack[++top] = item;
- }
- element pop()
- {
- if(top == -1)
- stackEmpty();
- return stack[top--];
- }
- void stackFull()
- {
- fprintf(stderr, "Stack is full, cannot add element\n");
- exit(EXIT_FAILURE);
- }
- void stackEmpty()
- {
- fprintf(stderr, "Stack is empty, cannot pop element\n");
- exit(EXIT_FAILURE);
- }
- void stackDisplay()
- {
- int i;
- if(isEmpty()) stackEmpty();
- printf("\nstack key list\n");
- for(i = 0; i < top + 1; i++){
- printf("stack[%d] : %d\n", i, stack[i].key);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment