diff options
| author | Steve Lee <me@xiangyangli.com> | 2017-12-02 06:03:52 +0800 |
|---|---|---|
| committer | Steve Lee <me@xiangyangli.com> | 2017-12-02 06:03:52 +0800 |
| commit | c3cf173d30db6cff2561696a46abfcdef538bf71 (patch) | |
| tree | 4fc46c542d759a4ec8da3b57afe00ec6323f3ab1 /Computer_Science/data_structures/chapter_3/stack_array.c | |
| parent | b46c49228497cb440467167bad3123c327bd620f (diff) | |
| download | 42-c3cf173d30db6cff2561696a46abfcdef538bf71.tar.xz 42-c3cf173d30db6cff2561696a46abfcdef538bf71.zip | |
category
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; +} |
