/* stack1.c * * a stack implementation in C * * Jim Mahoney | cs.bennington.college | MIT License | March 2021 */ #include #include #define STACK_SIZE 100 typedef struct _stack *stack; struct _stack { int items[STACK_SIZE]; int top; // index of top of stack; -1 if empty }; stack new_stack(){ stack s = malloc(sizeof(struct _stack)); s->top = -1; return s; } void free_stack(stack s){ free(s); } void stack_push(int i, stack s){ if (s->top < STACK_SIZE - 1){ s->top++; s->items[s->top] = i; } else { printf("Error: exceeded max stack size\n"); exit(-1); } } int stack_pop(stack s){ s->top--; return s->items[s->top + 1]; } int stack_peep(stack s){ return s->items[s->top]; } int stack_is_empty(stack s){ return s->top < 0; } int main(){ stack s = new_stack(); printf("push(1), push(2), then pop() until empty.\n"); stack_push(1, s); stack_push(2, s); while (! stack_is_empty(s)){ printf("%d\n", stack_pop(s)); } return 0; }