From 3ae2b3928739d947ef6ad792403ea1b00bf8bd4b Mon Sep 17 00:00:00 2001 From: HampusM Date: Mon, 13 Dec 2021 16:27:01 +0100 Subject: refactor: clean up --- stack.c | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) (limited to 'stack.c') diff --git a/stack.c b/stack.c index 651c446..de5807c 100644 --- a/stack.c +++ b/stack.c @@ -1,8 +1,24 @@ #include "stack.h" +#include #include -// Create a new stack -struct stack *new_stack(int capacity) +// Error handler for stack errors +void stack_error(int id) +{ + switch (id) + { + case 0: + printf("Error: Stack overflow\nBe kind and report this problem."); + break; + case 1: + printf("Error: Stack underflow\nBe kind and report this problem."); + break; + } + exit(1); +} + +// Creates a new stack +struct stack *create_stack(int capacity) { struct stack *pt = (struct stack *)malloc(sizeof(struct stack)); pt->max_size = capacity; @@ -11,31 +27,31 @@ struct stack *new_stack(int capacity) return pt; } -// Add a new item to a stack +// Adds 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); + stack_error(0); // Add an element and increase the top index pt->items[++pt->top] = x; } -// Get the topmost item of a stack +// Returns the topmost item of a stack int stack_peek(struct stack *pt) { // Check if the stack is empty if (pt->top == -1) - err(1); + stack_error(1); return pt->items[pt->top]; } -// Remove the topmost item of a stack +// Deletes the topmost item of a stack int stack_pop(struct stack *pt) { // Check for a stack underflow if (pt->top == -1) - err(0); + stack_error(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