diff options
| author | Steve Lee <me@xiangyangli.com> | 2017-10-17 00:12:32 +0800 |
|---|---|---|
| committer | Steve Lee <me@xiangyangli.com> | 2017-10-17 00:12:32 +0800 |
| commit | b46c49228497cb440467167bad3123c327bd620f (patch) | |
| tree | 7547f4da0694b7c85e57e7e56cd1f0e6f3cdc4d8 /data_structures/chapter_3/stack_array.c | |
| parent | 37f4cc25e5bcf68539d2b3828ecff5d72ae8c74b (diff) | |
| download | 42-b46c49228497cb440467167bad3123c327bd620f.tar.xz 42-b46c49228497cb440467167bad3123c327bd620f.zip | |
add
Diffstat (limited to 'data_structures/chapter_3/stack_array.c')
| -rw-r--r-- | data_structures/chapter_3/stack_array.c | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/data_structures/chapter_3/stack_array.c b/data_structures/chapter_3/stack_array.c new file mode 100644 index 0000000..4c23334 --- /dev/null +++ b/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; +} |
