From af4671acbc48446b0e0b3589b648854488f78e58 Mon Sep 17 00:00:00 2001 From: HampusM Date: Sat, 11 Dec 2021 20:18:16 +0100 Subject: refactor: fix formatting & move stack --- stack.c | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 stack.c (limited to 'stack.c') diff --git a/stack.c b/stack.c new file mode 100644 index 0000000..651c446 --- /dev/null +++ b/stack.c @@ -0,0 +1,41 @@ +#include "stack.h" +#include + +// Create a new stack +struct stack *new_stack(int capacity) +{ + struct stack *pt = (struct stack *)malloc(sizeof(struct stack)); + pt->max_size = capacity; + pt->top = -1; + pt->items = (int *)malloc(sizeof(int) * capacity); + return pt; +} + +// Add a new item to a stack +void stack_push(struct stack *pt, int x) +{ + // Avoid a overflow by checking if the stack is full + if (pt->top == pt->max_size - 1) + err(0); + // Add an element and increase the top index + pt->items[++pt->top] = x; +} + +// Get the topmost item of a stack +int stack_peek(struct stack *pt) +{ + // Check if the stack is empty + if (pt->top == -1) + err(1); + return pt->items[pt->top]; +} + +// Remove the topmost item of a stack +int stack_pop(struct stack *pt) +{ + // Check for a stack underflow + if (pt->top == -1) + err(0); + // Decrease the stack size by 1 and (optionally) return the popped element + return pt->items[pt->top--]; +} \ No newline at end of file -- cgit v1.2.3-18-g5258