diff --git a/stack.c b/stack.c new file mode 100644 index 0000000..ed1d4b9 --- /dev/null +++ b/stack.c @@ -0,0 +1,62 @@ +#include +#include +#include +#include + +#include "stack.h" + +struct Stack { + void** data; + int top_index; + int capacity; + int curr_size; +}; + +Stack* new_stack(int stack_size) { + assert(stack_size > 0); + Stack* my_stack = malloc(sizeof(Stack)); + my_stack->capacity = stack_size; + my_stack->data = malloc(stack_size); + my_stack->top_index = 0; + my_stack->curr_size = 0; + return my_stack; +} + +void stack_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; + stack->top_index++; + stack->curr_size++; + return; +} + +void* stack_pop(Stack* stack) { + assert( !(stack_isEmpty(stack)) ); + free(stack->data + stack->top_index); + stack->top_index--; + void* to_return = *(stack->data + stack->top_index); + *(stack->data + stack->top_index) = NULL; + + stack->curr_size--; + + return to_return; +} + +void* stack_peek(Stack* stack) { + void* to_return = *(stack->data + stack->top_index - 1); + return to_return; +} + +int stack_size(Stack* stack) { + return (stack->curr_size); +} + +bool stack_isEmpty(Stack* stack) { + if (stack_size(stack) == 0) { + return true; + } + return false; +} diff --git a/stack.h b/stack.h new file mode 100644 index 0000000..56ab7cf --- /dev/null +++ b/stack.h @@ -0,0 +1,11 @@ +#include + +typedef struct Stack Stack; + +Stack* new_stack(int stack_size); + +void stack_push(Stack* stack, void* element); +void* stack_pop(Stack* stack); +void* stack_peek(Stack* stack); +int stack_size(Stack* stack); +bool stack_isEmpty(Stack* stack);