diff options
Diffstat (limited to 'Computer_Science/data_structures/chapter_3/stack_array.c')
| -rw-r--r-- | Computer_Science/data_structures/chapter_3/stack_array.c | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/Computer_Science/data_structures/chapter_3/stack_array.c b/Computer_Science/data_structures/chapter_3/stack_array.c new file mode 100644 index 0000000..4c23334 --- /dev/null +++ b/Computer_Science/data_structures/chapter_3/stack_array.c @@ -0,0 +1,90 @@ +#include <stdio.h> +#include <stdlib.h> + +#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 >= 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; +} |
