-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.c
47 lines (39 loc) · 873 Bytes
/
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
#include "common.h"
#include "stack.h"
#define INITIAL_BUF_LEN 16
void stack_init(Stack *stack)
{
stack->buf = emalloc(sizeof(*stack->buf)*INITIAL_BUF_LEN, "stack init");
stack->buf_len = INITIAL_BUF_LEN;
stack->len = 0;
}
void stack_free(Stack *stack)
{
free(stack->buf);
}
size_t stack_len(Stack *stack)
{
return stack->len;
}
static void grow(Stack *stack)
{
stack->buf_len *= 2;
stack->buf = erealloc(stack->buf, sizeof(*stack->buf)*stack->buf_len,
"stack grow");
}
void stack_push(Stack *stack, void *val)
{
if (stack->len == stack->buf_len)
grow(stack);
stack->buf[stack->len++] = val;
}
void *stack_peek(Stack *stack)
{
assert(stack->len > 0);
return stack->buf[stack->len - 1];
}
void *stack_pop(Stack *stack)
{
assert(stack->len > 0);
return stack->buf[--stack->len];
}