74 lines
1.8 KiB
C
74 lines
1.8 KiB
C
|
|
#include "type_stack.h"
|
|
|
|
/************************/
|
|
/* Fonctions primitives */
|
|
/************************/
|
|
|
|
static void grow_stack(stack *thestack) {
|
|
thestack->array =
|
|
realloc(thestack->array, 2 * thestack->size_array * sizeof(void *));
|
|
if (thestack->array == NULL) {
|
|
ERROR("Erreur d'allocation mémoire");
|
|
}
|
|
thestack->size_array = 2 * thestack->size_array;
|
|
}
|
|
|
|
static void shrink_stack(stack *thestack) {
|
|
thestack->array =
|
|
realloc(thestack->array, thestack->size_array * sizeof(void *) / 2);
|
|
if (thestack->array == NULL) {
|
|
ERROR("Erreur d'allocation mémoire");
|
|
}
|
|
thestack->size_array = thestack->size_array / 2;
|
|
}
|
|
|
|
/* Création */
|
|
stack *create_stack(void) {
|
|
stack *thestack = malloc(sizeof(stack));
|
|
thestack->size_array = 1;
|
|
thestack->size_stack = 0;
|
|
thestack->array = malloc(sizeof(void *));
|
|
return thestack;
|
|
}
|
|
|
|
/* Suppression */
|
|
void delete_stack(stack *thestack) {
|
|
free(thestack->array);
|
|
free(thestack);
|
|
}
|
|
|
|
/* Test du vide */
|
|
bool isempty_stack(stack *thestack) {
|
|
return thestack->size_stack == 0;
|
|
}
|
|
|
|
/* Taille*/
|
|
uint size_stack(stack *thestack) { return thestack->size_stack; }
|
|
|
|
/* Lecture */
|
|
void *read_stack(stack *thestack, const uint index) { return thestack->array[index]; }
|
|
|
|
/* Dépiler */
|
|
void *pop(stack *thestack) {
|
|
if (isempty_stack(thestack)) {
|
|
ERROR("La pile est vide.");
|
|
}
|
|
void *v = thestack->array[(thestack->size_stack) - 1];
|
|
thestack->size_stack -= 1;
|
|
if (thestack->size_stack <= thestack->size_array / 4 &&
|
|
thestack->size_array > 1) {
|
|
shrink_stack(thestack);
|
|
}
|
|
return v;
|
|
}
|
|
|
|
/* Empiler */
|
|
void push(void *val, stack *thestack) {
|
|
if (thestack->size_array <= thestack->size_stack) {
|
|
grow_stack(thestack);
|
|
}
|
|
thestack->size_stack += 1;
|
|
thestack->array[thestack->size_stack - 1] = val;
|
|
}
|