-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
81 lines (58 loc) · 1.54 KB
/
Copy pathstack.c
File metadata and controls
81 lines (58 loc) · 1.54 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <assert.h>
#include <stdlib.h>
#include "stack.h"
#include "src/utils/macro_utils.h"
#include "stdio.h"
static bool IsStackFull(Stack* stack) {
REPORT(stack);
return stack->top == stack->capacity - 1;
}
bool IsEmptyStack(Stack* stack) {
REPORT(stack);
return stack->top == -1;
}
void StackPush(Stack* stack, void* item) {
REPORT(stack);
if (IsStackFull(stack)) {
stack->capacity += INCREASE_CONST;
stack->array = realloc(stack->array, stack->capacity * sizeof(void*));
}
stack->array[++stack->top] = item;
}
void* StackPop(Stack* stack) {
REPORT(stack);
void* p = NULL;
void* mem = NULL;
if (IsEmptyStack(stack)) {
return NULL;
}
p = stack->array[stack->top--];
if (stack->top + 1 - stack->capacity >= DECREASE_CONST)
if ((mem = realloc(stack->array, stack->top + 1)) != NULL) {
stack->array = mem;
}
return p;
}
void* StackPeek(Stack* stack) {
REPORT(stack);
if (IsEmptyStack(stack))
return NULL;
return stack->array[stack->top];
}
Stack* StackConstructor(long capacity) {
Stack* stack = NULL;
if ((stack = (Stack*) calloc(1, sizeof(Stack))) != NULL) {
stack->capacity = capacity > 0 ? capacity : 0;
stack->top = -1;
if ((stack->array = calloc(stack->capacity, sizeof(void*))) == NULL) {
assert("[!] Calloc error [!]" && 0);
}
}
return stack;
}
void StackDestructor(Stack* stack) {
REPORT(stack);
if (stack->array)
free(stack->array);
free(stack);
}