-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
58 lines (49 loc) · 1.1 KB
/
stack.c
File metadata and controls
58 lines (49 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "stack.h"
#include "dumb-logger/logger.h"
#include <stdio.h>
#include <limits.h> // pour INT_MIN
#include <stdlib.h>
/* extrait du fichier stack.h ; représentation d'une pile
typedef struct stack_struct {
int* mem;
int capacity;
int sp; // stack pointer
} stack;
*/
void stack_init(stack* s, int capacity) { int i;
s->capacity = capacity;
s->mem = malloc(sizeof(int)*capacity);
for (i = 0; i < s->capacity; i++) {
s->mem[i] = INT_MIN;
}
s->sp = 0;
}
int stack_push(stack* s, int value) {
if (s->sp == s->capacity - 1) {
printf("Stackoverflow error : no more space to push to stack \n");
return -1;
}
s->mem[s->sp] = value;
s->sp++;
return 0;
}
int stack_pop(stack* s) {
if (s->sp == 0) {
printf("Stack empty error : no value to pop from stack\n");
return -1;
}
s->sp--;
return s->mem[s->sp];
}
void stack_print(stack* s) { int i;
logger_info("Representation de la pile : \n");
logger_info("Adresse - Valeur\n");
for (i = 0; i < s->sp; i++) {
logger_info(" %2d %4d\n", i, s->mem[i]);
}
}
void stack_destroy(stack* s) {
free(s->mem);
s->capacity = 0;
s->sp = 0;
}