-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.c
92 lines (68 loc) · 1.68 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
#include "stack.h"
#include <stdlib.h>
#include <string.h>
/*
Generic dynamically allocated stack.
Pushing automatically allocates and copies
the item so you can pass pointer to a variable
allocated on local function stack.
When popping immediately copy the item because
the pointer can be invalidated by future pushes.
*/
Stack stackAlloc(size_t itemSize, int capacityOverhead)
{
Stack st;
if(capacityOverhead <= 0)
capacityOverhead = 1;
st.capacityOverheadSz = (size_t)capacityOverhead * itemSize;
st.capacitySz = st.capacityOverheadSz;
st.itemSz = itemSize;
st.sz = 0;
st.itemPtr = NULL;
st.index = -1;
if(capacityOverhead != 0)
st.items = malloc(st.capacitySz);
else
st.items = NULL;
return st;
}
void stackPush(Stack *stack, void *itemPtr)
{
if(stack->sz == stack->capacitySz)
{
stack->capacitySz += stack->capacityOverheadSz;
stack->items = realloc(stack->items, stack->capacitySz);
}
stack->sz += stack->itemSz;
stack->index++;
stack->itemPtr = stack->items + (stack->itemSz * stack->index);
memcpy(stack->itemPtr, itemPtr, stack->itemSz);
}
void *stackPop(Stack *stack)
{
if(stack->sz == 0)
return NULL;
stack->index--;
stack->sz -= stack->itemSz;
void *itemPtr = stack->itemPtr;
stack->itemPtr -= stack->itemSz;
return itemPtr;
}
void stackFree(Stack stack)
{
free(stack.items);
}
void stackClear(Stack *stack)
{
stack->index = -1;
stack->sz = 0;
stack->itemPtr = NULL;
}
inline int stackGetItemCount(Stack *stack)
{
return stack->index + 1;
}
inline bool stackNotEmpty(Stack *stack)
{
return stack->sz != 0;
}