#include #include #include "stack_array.h" #define EMPTY_TOS (-1) #define MIN_STACK_SIZE (5) struct stack_record { int capacity; int top_of_stack; elem *array; }; stack create_stack(int max_elements) { stack s; if(max_elements < MIN_STACK_SIZE) printf("size too small.\n"); s = malloc(sizeof(struct stack_record)); if(s == NULL) printf("out of space"); s->array = malloc(sizeof(elem) * max_elements); if(s->array == NULL) printf("out of space"); s->capacity = max_elements; make_empty(s); return s; } void dispose_stack(stack s) { if(s != NULL) { free(s->array); free(s); } } int is_empty(stack s) { return s->top_of_stack == EMPTY_TOS; } void make_empty(stack s) { s->top_of_stack = EMPTY_TOS; } void push(elem x, stack s) { if(s->top_of_stack >= s->capacity) printf("full stack"); else s->array[++s->top_of_stack] = x; } elem top(stack s) { if(!is_empty(s)) return s->array[s->top_of_stack]; printf("empty stack"); return 0; } void pop(stack s) { if(!is_empty(s)) s->top_of_stack--; printf("empty stack"); } elem top_and_pop(stack s) { if(!is_empty(s)) /* take care of this, before return, s->top_of_stack is already dec. */ return s->array[s->top_of_stack--]; printf("empty stack"); return 0; } int main() { stack s = create_stack(100); push(1, s); push(2, s); push(3, s); printf("%d\n", top_and_pop(s)); printf("%d\n", top_and_pop(s)); return 0; }