-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
111 lines (104 loc) · 2.58 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/* IFJ20 - Stack library
* Authors:
* Mario Harvan, xharva03
*/
#include "stack.h"
#include "error.h"
#include <stdlib.h>
#include <stdio.h>
#define DEFAULT_STACK_SIZE 20
Stack *stackInit()
{
Stack *tmp = malloc(sizeof(Stack));
if (tmp == NULL)
throw_error_fatal(INTERNAL_ERROR, "%s", "Couldn't allocate memory!");
tmp->size = DEFAULT_STACK_SIZE;
tmp->arrPtr = 0;
tmp->stackPosition = 0;
tmp->itemCnt = 0;
tmp->arrPtr = malloc(sizeof(Token) * DEFAULT_STACK_SIZE);
if (tmp->arrPtr == NULL)
throw_error_fatal(INTERNAL_ERROR, "%s", "Couldn't allocate memory!");
return tmp;
}
bool stackIsEmpty(Stack *stack)
{
if (stack != NULL)
{
if (stack->itemCnt == 0)
return true;
else
return false;
}
return false;
}
Token stackPeek(Stack *stack)
{
Token empty;
empty.type = TOKEN_EOF;
if (stack != NULL)
{
if (stackIsEmpty(stack) == false)
return stack->arrPtr[stack->stackPosition];
}
return empty;
}
void stackPush(Stack *stack, Token token)
{
if (stack != NULL)
{
if (stackIsEmpty(stack) == true)
{
stack->arrPtr[0] = token;
stack->itemCnt++;
}
else if (stack->size > stack->itemCnt)
{
stack->stackPosition++;
stack->arrPtr[stack->stackPosition] = token;
stack->itemCnt++;
}
else
{
//resize stack if needed
stack->arrPtr = realloc(stack->arrPtr, sizeof(Token) * stack->size * 2);
if (stack->arrPtr == NULL)
throw_error_fatal(INTERNAL_ERROR, "%s", "Couldn't allocate memory!");
stack->size = stack->size * 2;
stack->stackPosition++;
stack->arrPtr[stack->stackPosition] = token;
stack->itemCnt++;
}
}
}
Token stackPop(Stack *stack)
{
Token empty;
empty.type = TOKEN_EOF;
if (stack != NULL)
{
if (stackIsEmpty(stack) == true)
return empty;
else
{
stack->itemCnt--;
if (stack->stackPosition != 0)
{
stack->stackPosition--;
return stack->arrPtr[stack->stackPosition + 1];
}
else
return stack->arrPtr[0];
}
}
return empty;
}
void stackFree(Stack *stack)
{
if (stack != NULL)
{
free(stack->arrPtr);
free(stack);
stack = NULL;
}
}