forked from thewhoo/ifj15
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
92 lines (75 loc) · 1.64 KB
/
stack.c
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
82
83
84
85
86
87
88
89
90
91
92
/*
* Course IFJ @ FIT VUT Brno, 2015
* IFJ15 Interpreter Project
*
* Authors:
* Lukas Osadsky - xosads00
* Pavol Plaskon - xplask00
* Pavel Pospisil - xpospi88
* Matej Postolka - xposto02
*
* Unless otherwise stated, all code is licensed under a
* GNU General Public License v2.0
*
*/
#include <stdlib.h>
#include "stack.h"
#include "error.h"
#include "galloc.h"
#include "enums.h"
#include "shared.h"
#define DEFAULT_STACK_SIZE 15
#define AUTORESIZE_COEF 2
TStack* stack_init()
{
TStack *stack = gmalloc(sizeof(TStack));
stack->data = gmalloc(DEFAULT_STACK_SIZE * sizeof(void *));
stack->capacity = DEFAULT_STACK_SIZE;
stack->used = 0;
return stack;
}
TStack* stack_copy(TStack *s)
{
TStack *sNew = gmalloc(sizeof(TStack));
sNew->data = gmalloc(sizeof(void *) * s->capacity);
for(int i = 0; i < s->used; i++)
sNew->data[i] = s->data[i];
return sNew;
}
void stack_clear(TStack *stack)
{
stack->used = 0;
}
void stack_free(TStack* stack)
{
gfree(stack->data);
gfree(stack);
}
int stack_push(TStack* stack, void* item)
{
if(stack->capacity <= stack->used)
{
stack->data = grealloc(stack->data,
sizeof(void *) * stack->capacity * AUTORESIZE_COEF);
stack->capacity = stack->capacity * AUTORESIZE_COEF;
}
stack->data[stack->used] = item;
(stack->used)++;
return 0;
}
void stack_pop(TStack *stack)
{
if(stack->used > 0)
(stack->used)--;
}
void* stack_top(TStack *stack)
{
if(stack->used > 0)
return stack->data[stack->used - 1];
else
return NULL;
}
int stack_empty(TStack *stack)
{
return (stack->used == 0);
}