From 425ed5ab81260bc04a94a55aa8373a19e7f19f50 Mon Sep 17 00:00:00 2001 From: Hampus Date: Thu, 7 Jan 2021 18:14:09 +0100 Subject: fix: add indentation & optimize stack functions --- mazerator.c | 76 +++++++++++++++++++++++++------------------------------------ 1 file changed, 31 insertions(+), 45 deletions(-) (limited to 'mazerator.c') diff --git a/mazerator.c b/mazerator.c index 25a7f7d..6c24ec0 100644 --- a/mazerator.c +++ b/mazerator.c @@ -5,75 +5,61 @@ #include #include +// Error handling +void err(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); +} + // The fundementals for the maze-generation algoritm // A stack data-structure struct stack { - int max_size; - int top; - int *items; + int max_size; + int top; + int *items; }; // 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; -} - -// Check if a stack is empty -int stack_is_empty(struct stack *pt) -{ - return pt->top == -1; -} - -// Check if a stack is full -int stack_is_full(struct stack *pt) -{ - return pt->top == pt->max_size - 1; + 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 (stack_is_full(pt)) - { - printf("Overflow error\nProgram terminated\n"); - exit(EXIT_FAILURE); - } - - // Add an element and increase the top index - pt->items[++pt->top] = 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 (!stack_is_empty(pt)) - return pt->items[pt->top]; - else - exit(EXIT_FAILURE); + // 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 (stack_is_empty(pt)) - { - printf("Underflow error\nProgram terminated\n"); - exit(EXIT_FAILURE); - } - - // Decrease the stack size by 1 and (optionally) return the popped element - return pt->items[pt->top--]; + // 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--]; } // Get a position in the maze from coordinates y and x -- cgit v1.2.3-18-g5258