diff options
author | Hampus <hampus@hampusmat.com> | 2021-12-14 00:01:35 +0100 |
---|---|---|
committer | Hampus <hampus@hampusmat.com> | 2021-12-14 00:01:35 +0100 |
commit | 88d8be06f3e5411db6faa59db12210b6079f7d21 (patch) | |
tree | 8e05fca5d76cb8734fc30e50297471ca72cdaa20 /src/position_stack.c | |
parent | af93edd8433634d82e855e9c9bcbca249a476977 (diff) |
refactor: restructure project
Diffstat (limited to 'src/position_stack.c')
-rw-r--r-- | src/position_stack.c | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/position_stack.c b/src/position_stack.c new file mode 100644 index 0000000..3d546b8 --- /dev/null +++ b/src/position_stack.c @@ -0,0 +1,69 @@ +#include "position_stack.h" +#include <stdio.h> +#include <stdlib.h> + +// Error handler for stack errors +void stack_error(int err) +{ + switch (err) + { + case STACK_ERR_OVERFLOW: + printf("Error: Stack overflow\nBe kind and report this problem."); + break; + case STACK_ERR_UNDERFLOW: + printf("Error: Stack underflow\nBe kind and report this problem."); + break; + } + + exit(1); +} + +// Creates a new stack +struct PositionStack *create_pos_stack(int capacity) +{ + struct PositionStack *stack_pt = malloc(sizeof(struct PositionStack)); + + stack_pt->max_size = capacity; + stack_pt->top = -1; + stack_pt->items = malloc(sizeof(struct Position) * capacity); + + return stack_pt; +} + +// Adds a new item to a stack +void pos_stack_push(struct PositionStack *stack_pt, struct Position pos) +{ + // Avoid a overflow by checking if the stack is full + if (stack_pt->top == stack_pt->max_size - 1) + { + stack_error(STACK_ERR_OVERFLOW); + } + + // Add an element and increase the top index + stack_pt->items[++stack_pt->top] = pos; +} + +// Returns the topmost item of a stack +struct Position pos_stack_peek(struct PositionStack *stack_pt) +{ + // Avoid a underflow by checking if the stack is empty + if (stack_pt->top == -1) + { + stack_error(STACK_ERR_UNDERFLOW); + } + + return stack_pt->items[stack_pt->top]; +} + +// Deletes the topmost item of a stack +struct Position pos_stack_pop(struct PositionStack *stack_pt) +{ + // Avoid a underflow by checking if the stack is empty + if (stack_pt->top == -1) + { + stack_error(STACK_ERR_UNDERFLOW); + } + + // Decrease the stack size by 1 and return the popped element + return stack_pt->items[stack_pt->top--]; +}
\ No newline at end of file |