From b6fe9fc6a4f31d4fa0ddad7fdfd3324cd1c88d3e Mon Sep 17 00:00:00 2001 From: verdant Date: Sun, 24 May 2026 13:55:39 +0800 Subject: Initial commit --- stack.c | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 stack.c (limited to 'stack.c') diff --git a/stack.c b/stack.c new file mode 100644 index 0000000..1014785 --- /dev/null +++ b/stack.c @@ -0,0 +1,65 @@ +#include "./stack.h" +#include +#include + +bool stack_is_empty(stack *s) +{ + if (!s || s->top == -1) { + return true; + } + + return false; +} + +stack *new_stack(size_t size) +{ + stack *s = malloc(sizeof(stack)); + if (!s) + return NULL; + + s->data = malloc(size * sizeof(void *)); + if (!s->data) { + free(s); + return NULL; + } + + s->capacity = size; + s->top = -1; + return s; +} + +void free_stack(stack *s) +{ + if (!s) + return; + + free(s->data); + free(s); +} + +void *pop(stack *s) +{ + if (stack_is_empty(s)) + return NULL; + return s->data[s->top--]; +} + +void *peek(stack *s) +{ + if (stack_is_empty(s)) + return NULL; + return s->data[s->top]; +} + +void *push(stack *s, void *data) +{ + if (!s) + return NULL; + + if (s->top + 1 >= s->capacity) { + s->capacity *= 2; + s->data = realloc(s->data, sizeof(void *) * s->capacity); + } + + return s->data[++s->top] = data; +} -- cgit v1.2.3