From 9584ab5540c99b1ecb19320dbc385a12d4bfa0b2 Mon Sep 17 00:00:00 2001 From: jonas <jonas.stirnemann@etu.hesge.ch> Date: Wed, 17 Nov 2021 12:01:19 +0100 Subject: [PATCH] Realloc in push --- stack/include/stack.h | 7 +++---- stack/src/stack.c | 13 +++++++++---- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/stack/include/stack.h b/stack/include/stack.h index d27e992..92c9855 100644 --- a/stack/include/stack.h +++ b/stack/include/stack.h @@ -10,22 +10,21 @@ #include <stdint.h> #include <stdlib.h> - - #ifndef _JSTACK_H_ #define _JSTACK_H_ // DEFINES -#define MAX_CAPACITY 500 +#define INCREMENT_STACK 100 typedef struct { + uint64_t max; int64_t top; int32_t *data; }stack_t; // PROTOTYPE FUNCTIONS -int32_t* create_stack(); +int32_t* create_stack(uint64_t capa); void stack_push(stack_t* st, int32_t val); int32_t stack_pop(stack_t* st); int32_t stack_peek(stack_t st); diff --git a/stack/src/stack.c b/stack/src/stack.c index b5bfae5..069ca2a 100644 --- a/stack/src/stack.c +++ b/stack/src/stack.c @@ -7,21 +7,26 @@ #include "../include/stack.h" -int32_t* create_stack() +int32_t* create_stack(uint64_t capa) { stack_t* st = malloc(sizeof(stack_t)); - st->data = malloc(MAX_CAPACITY * sizeof(int32_t)); + st->max = capa; + st->data = malloc(st->max * sizeof(int32_t)); st->top = -1; } void stack_push(stack_t* st, int32_t val) { + // UP CAPACITY WHEN MAX IS REACHED + if(st->top == st->max) + { + realloc(st->data, st->max + INCREMENT_STACK); + } st->data[++st->top] = val; } int32_t stack_pop(stack_t* st) { - return st->data[st->top--]; } @@ -32,7 +37,7 @@ int32_t stack_peek(stack_t st) bool stack_is_full(stack_t st) { - return st.top == MAX_CAPACITY; + return st.top == st.max; } bool stack_is_empty(stack_t st) -- GitLab