diff options
Diffstat (limited to 'stack2.c')
| -rw-r--r-- | stack2.c | 23 |
1 files changed, 13 insertions, 10 deletions
| @@ -1,13 +1,13 @@ | |||
| 1 | #include <stdbool.h> | ||
| 1 | #include <stdio.h> | 2 | #include <stdio.h> |
| 2 | #include <stdlib.h> | 3 | #include <stdlib.h> |
| 3 | #include <stdbool.h> | ||
| 4 | 4 | ||
| 5 | #include "util.h" | 5 | #include "util.h" |
| 6 | 6 | ||
| 7 | typedef int T; | 7 | typedef int T; |
| 8 | 8 | ||
| 9 | struct stack { | 9 | struct stack { |
| 10 | T *array; | 10 | T * array; |
| 11 | size_t sz, p; | 11 | size_t sz, p; |
| 12 | }; | 12 | }; |
| 13 | 13 | ||
| @@ -15,8 +15,8 @@ void | |||
| 15 | stack_init(struct stack *stack) | 15 | stack_init(struct stack *stack) |
| 16 | { | 16 | { |
| 17 | stack->array = NULL; | 17 | stack->array = NULL; |
| 18 | stack->sz = 0; | 18 | stack->sz = 0; |
| 19 | stack->p = 0; | 19 | stack->p = 0; |
| 20 | } | 20 | } |
| 21 | 21 | ||
| 22 | bool | 22 | bool |
| @@ -25,7 +25,7 @@ stack_push(struct stack *stack, T data) | |||
| 25 | if ( stack->array == NULL ) { | 25 | if ( stack->array == NULL ) { |
| 26 | if ( (stack->array = malloc(10 * sizeof(*stack->array))) != NULL ) { | 26 | if ( (stack->array = malloc(10 * sizeof(*stack->array))) != NULL ) { |
| 27 | stack->sz = 10; | 27 | stack->sz = 10; |
| 28 | stack->p = 0; | 28 | stack->p = 0; |
| 29 | } | 29 | } |
| 30 | else { | 30 | else { |
| 31 | ERROR("out of memory"); | 31 | ERROR("out of memory"); |
| @@ -35,11 +35,11 @@ stack_push(struct stack *stack, T data) | |||
| 35 | 35 | ||
| 36 | if ( stack->p == stack->sz ) { | 36 | if ( stack->p == stack->sz ) { |
| 37 | size_t new_sz; | 37 | size_t new_sz; |
| 38 | T *new_array; | 38 | T * new_array; |
| 39 | 39 | ||
| 40 | if ( (new_array = realloc(stack->array, (new_sz = (stack->sz * 3 / 2)) * sizeof(*stack->array))) != NULL ) { | 40 | if ( (new_array = realloc(stack->array, (new_sz = (stack->sz * 3 / 2)) * sizeof(*stack->array))) != NULL ) { |
| 41 | stack->array = new_array; | 41 | stack->array = new_array; |
| 42 | stack->sz = new_sz; | 42 | stack->sz = new_sz; |
| 43 | } | 43 | } |
| 44 | else { | 44 | else { |
| 45 | ERROR("out of memory"); | 45 | ERROR("out of memory"); |
| @@ -55,7 +55,11 @@ bool | |||
| 55 | stack_pop(struct stack *stack, T *data) | 55 | stack_pop(struct stack *stack, T *data) |
| 56 | { | 56 | { |
| 57 | if ( stack->p != 0 ) { | 57 | if ( stack->p != 0 ) { |
| 58 | *data = stack->array[--stack->p]; | 58 | --stack->p; |
| 59 | |||
| 60 | if ( data != NULL ) { | ||
| 61 | *data = stack->array[stack->p]; | ||
| 62 | } | ||
| 59 | return true; | 63 | return true; |
| 60 | } | 64 | } |
| 61 | else | 65 | else |
| @@ -97,4 +101,3 @@ main() | |||
| 97 | 101 | ||
| 98 | return EXIT_SUCCESS; | 102 | return EXIT_SUCCESS; |
| 99 | } | 103 | } |
| 100 | |||
