diff --git a/stack.c b/stack.c new file mode 100644 index 0000000..2ab2791 --- /dev/null +++ b/stack.c @@ -0,0 +1,70 @@ +#include +#include +#include + +typedef int bool; +#define true 1 +#define false 0 + +struct stack { + int top; + int *data; + int size; + +}; + +void stack_push(struct stack *s, int e); +int stack_pop(struct stack *s); +bool stack_empty(struct stack *s); +bool stack_full(struct stack *s); +void stack_clear(struct stack *s); +void stack_free(struct stack* s); + +struct stack* stack_create(int size) { + struct stack* s = (struct stack*)malloc(sizeof(struct stack)); + s->top = -1; + s->data = (int*)malloc(sizeof(int)*size); + s->size = size; + return s; +} + +void stack_push(struct stack *s, int e) { + assert(!stack_full(s)); + s->data[++s->top] = e; +} + +int stack_pop(struct stack *s) { + assert(!stack_empty(s)); + return s->data[s->top--]; +} + +bool stack_empty(struct stack *s) { + return (s->top == -1); +} + +bool stack_full(struct stack *s) { + return (s->top == s->size - 1); +} + +void stack_clear(struct stack *s) { + s->top = -1; +} + +void stack_free(struct stack* s) { + free(s->data); + free(s); +} + +int main( int argc, char *argv[] ) { + struct stack* s = stack_create(10); + + for(int i = 0; !stack_full(s); i++) { + stack_push(s, i); + } + + while(!stack_empty(s)) { + printf("%d\n",stack_pop(s)); + } + + return 0; +}