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 /data_structures/chapter_3/stack.c | |
| parent | b46c49228497cb440467167bad3123c327bd620f (diff) | |
| download | 42-c3cf173d30db6cff2561696a46abfcdef538bf71.tar.xz 42-c3cf173d30db6cff2561696a46abfcdef538bf71.zip | |
category
Diffstat (limited to 'data_structures/chapter_3/stack.c')
| -rw-r--r-- | data_structures/chapter_3/stack.c | 120 |
1 files changed, 0 insertions, 120 deletions
diff --git a/data_structures/chapter_3/stack.c b/data_structures/chapter_3/stack.c deleted file mode 100644 index a27869f..0000000 --- a/data_structures/chapter_3/stack.c +++ /dev/null @@ -1,120 +0,0 @@ -#include <stdio.h> -#include <stdlib.h> - -#include "stack.h" - -/* Stack implementation is a linked list with a header */ -struct node -{ - elem data; - ptr_to_node next; -}; - -int is_empty(stack s) -{ - return s->next == NULL; -} - -stack create_stack() -{ - stack s; - - s = malloc(sizeof(struct node)); - if(s == NULL) - printf("error"); - make_empty(s); - return s; -} - -void make_empty(stack s) -{ - if(s == NULL) - printf("must create a stack first"); - else - while(!is_empty(s)) - pop(s); -} - -void push(elem x, stack s) -{ - ptr_to_node tmp; - - tmp = malloc(sizeof(struct node)); - if(tmp == NULL) - printf("out of space"); - else { - tmp->data = x; - tmp->next = s->next; - s->next = tmp; - } -} - -void pop(stack s) -{ - if(!is_empty(s)) { - ptr_to_node tmp = s->next; - s->next = s->next->next; - free(tmp); - } else - printf("Empty stack"); -} - -elem top(stack s) -{ -// if(is_empty(s)) -// printf("empty stack"); -// else -// return s->next->data; -// -// return -1; -// -/* tune version */ - if(!is_empty(s)) - return s->next->data; - - printf("empty stack"); - return 0; -} - -void print_stack(stack s) -{ - printf("--------\n"); - while(!is_empty(s)) { - printf(" %d\n", s->next->data); - s = s->next; - } - printf("--------\n"); -} - -void test() -{ - stack s; - s = create_stack(); - push(1, s); - push(2, s); - print_stack(s); - - push(3, s); - push(4, s); - push(5, s); - print_stack(s); - printf("%d\n",top(s)); - - pop(s); - print_stack(s); - - pop(s); - pop(s); - pop(s); - pop(s); - pop(s); - pop(s); - - print_stack(s); -} - -int main() -{ - test(); - return 0; -} |
