#include "c1_stack.h" // initialize data structure void stack_create(Stack *s) { s->index = -1; s->elements = (int *) malloc(MAX_ELEMENTS * sizeof(int)); } // remove data allocated by stack_create void stack_delete(Stack *s) { free(s->elements); } // push void stack_push(Stack *s, int v) { ++s->index; if (s->index == MAX_ELEMENTS) { printf("stack is full\n"); exit(1); } s->elements[s->index] = v; } // pop void stack_pop(Stack *s) { if (s->index == -1) { printf("stack is empty\n"); exit(1); } --s->index; } // return element on top int stack_top(Stack *s) { if (s->index == -1) { printf("stack is empty\n"); exit(1); } return s->elements[s->index]; } // return 1 if stack is empty, 0 otherwise int stack_is_empty(Stack *s) { return (s->index == -1) ? 1 : 0; } // main int main() { int i, sum = 0; Stack s; stack_create(&s); for (i = 1; i<=10; ++i) { stack_push(&s, i); } while (!stack_is_empty(&s)) { sum += stack_top(&s); stack_pop(&s); } printf("sum = %d\n", sum); stack_delete(&s); return 0; }