diff options
| author | mo khan <mo.khan@gmail.com> | 2020-08-16 17:26:38 -0600 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2020-08-16 17:26:38 -0600 |
| commit | b8e927bd7ba60ca732e9b805d51a9583fd4f6419 (patch) | |
| tree | 3724c20df8ba95eaf92ede1eea2041099edc7b94 /src/02/03/stack.c | |
| parent | 18a7345a0b2514e26bef935da366b3cc631115be (diff) | |
Calculate the size of a binary tree
Diffstat (limited to 'src/02/03/stack.c')
| -rw-r--r-- | src/02/03/stack.c | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/src/02/03/stack.c b/src/02/03/stack.c new file mode 100644 index 0000000..ba3655d --- /dev/null +++ b/src/02/03/stack.c @@ -0,0 +1,52 @@ +#include "stack.h" +#include <stdlib.h> + +Node *node_init(void *data) { + Node *node = malloc(sizeof(Node)); + node->next = NULL; + node->data = data; + return node; +} + +Stack *stack_init() { + Stack *stack = malloc(sizeof(Stack)); + stack->head = NULL; + return stack; +} + +int stack_size(Stack *self) { + if (!self || !self->head) + return 0; + + int count = 0; + Node *current = self->head; + while (current) { + ++count; + current = current->next; + } + + return count; +} + +void *stack_peek(Stack *self) { + if (self->head) + return self->head->data; + return NULL; +} + +void stack_push(Stack *stack, void *data) { + Node *node = node_init(data); + node->next = stack->head; + stack->head = node; +} + +void *stack_pop(Stack *self) { + if (self->head) { + Node *tmp = self->head; + void *data = tmp->data; + self->head = self->head->next; + free(tmp); + return data; + } + return NULL; +} |
