From 01be5ed038c57359cf156c7cc4540117ed256ffc Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Wed, 12 Apr 2023 19:49:56 -0500 Subject: [PATCH] First commit --- stack.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 stack.c diff --git a/stack.c b/stack.c new file mode 100644 index 0000000..b7177fb --- /dev/null +++ b/stack.c @@ -0,0 +1,63 @@ +#include +#include + +typedef struct { + void** data; + int top_index; + int capacity; + int curr_size; +} Stack; + +Stack* new_stack(int stack_size) { + Stack* stack = malloc(sizeof(Stack)); + stack->capacity = stack_size; + stack->data = malloc(stack_size); + stack->top_index = 0; + stack->curr_size = 0; + return stack; +} + +void push(Stack* stack,void* element) { + if (stack->curr_size >= stack->capacity-1) { + stack->data = realloc(stack->data, stack->capacity*2); + stack->capacity *= 2; + } + *(stack->data + stack->top_index) = element; + printf("Adding to index %d\n",stack->top_index); + stack->top_index++; + stack->curr_size++; + return; +} + +void* pop(Stack* stack) { + stack->top_index--; + void* to_return = *(stack->data + stack->top_index); + *(stack->data + stack->top_index) = NULL; + + stack->curr_size--; + + return to_return; +} + +void* peek(Stack* stack) { + void* to_return = *(stack->data + stack->top_index - 1); + return to_return; +} + +int size(Stack* stack) { + return (stack->curr_size); +} + +void main() { + Stack* stack = new_stack(10); + int a = 2; + int b = 3; + int c = 4; + push(stack,(void *)&a); + push(stack,(void *)&b); + push(stack,(void *)&c); + printf("%d\n",*( (int *) pop(stack))); + printf("%d\n",*( (int *) pop(stack))); + printf("%d\n",*( (int *) pop(stack))); +// printf("%d\n",size(stack)); +}