[604e76d] | 1 | #include <stdlib.h> |
---|
| 2 | #include "c-stack.h" |
---|
| 3 | |
---|
| 4 | struct stack_node { |
---|
[81e8ab0] | 5 | void * value; |
---|
| 6 | struct stack_node * next; |
---|
[604e76d] | 7 | }; |
---|
| 8 | |
---|
[81e8ab0] | 9 | void clear_stack( struct stack * s, void (*free_el)( void * ) ) { |
---|
| 10 | for ( struct stack_node * next = s->head; next; ) { |
---|
| 11 | struct stack_node * crnt = next; |
---|
| 12 | next = crnt->next; |
---|
| 13 | free_el( crnt->value ); |
---|
| 14 | free( crnt ); |
---|
[604e76d] | 15 | } |
---|
[81e8ab0] | 16 | s->head = NULL; |
---|
[604e76d] | 17 | } |
---|
| 18 | |
---|
| 19 | struct stack new_stack() { return (struct stack){ NULL }; /***/ } |
---|
| 20 | |
---|
[81e8ab0] | 21 | void copy_stack( struct stack * s, const struct stack * t, void * (*copy)( const void * ) ) { |
---|
| 22 | struct stack_node ** crnt = &s->head; |
---|
| 23 | for ( struct stack_node * next = t->head; next; next = next->next ) { |
---|
| 24 | *crnt = malloc( sizeof(struct stack_node) ); /***/ |
---|
| 25 | (*crnt)->value = copy( next->value ); |
---|
| 26 | crnt = &(*crnt)->next; |
---|
[604e76d] | 27 | } |
---|
[81e8ab0] | 28 | *crnt = NULL; |
---|
[604e76d] | 29 | } |
---|
[8b001bd] | 30 | struct stack * assign_stack( struct stack * s, const struct stack * t, |
---|
| 31 | void * (*copy_el)( const void * ), void (*free_el)( void * ) ) { |
---|
[e59f0bf] | 32 | if ( s->head == t->head ) return s; |
---|
| 33 | clear_stack( s, free_el ); /***/ |
---|
| 34 | copy_stack( s, t, copy_el ); /***/ |
---|
| 35 | return s; |
---|
| 36 | } |
---|
[604e76d] | 37 | |
---|
[81e8ab0] | 38 | _Bool stack_empty( const struct stack * s ) { return s->head == NULL; } |
---|
[604e76d] | 39 | |
---|
[860f19f] | 40 | void push_stack( struct stack * s, void * v ) { |
---|
[81e8ab0] | 41 | struct stack_node * n = malloc( sizeof(struct stack_node) ); /***/ |
---|
[860f19f] | 42 | *n = (struct stack_node){ v, s->head }; /***/ |
---|
[604e76d] | 43 | s->head = n; |
---|
| 44 | } |
---|
| 45 | |
---|
[81e8ab0] | 46 | void * pop_stack( struct stack * s ) { |
---|
| 47 | struct stack_node * n = s->head; |
---|
[604e76d] | 48 | s->head = n->next; |
---|
[81e8ab0] | 49 | void * v = n->value; |
---|
| 50 | free( n ); |
---|
| 51 | return v; |
---|
[604e76d] | 52 | } |
---|