-
Notifications
You must be signed in to change notification settings - Fork 3
/
stack.c
86 lines (74 loc) · 1.41 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
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
#include "wrapper.h"
struct stack {
void **buf;
int top;
int size;
};
stack_t *stack_init(int n)
{
stack_t *stack;
assert(n > 0);
stack = xmalloc(sizeof(stack_t));
stack->buf = xmalloc(n * sizeof(void*));
stack->top = 0;
stack->size = n;
return stack;
}
bool stack_push(stack_t *stack, void *data)
{
if (stack->top < stack->size) {
stack->buf[stack->top++] = data;
return true;
}
return false;
}
void *stack_pop(stack_t *stack)
{
if (stack->top > 0)
return stack->buf[--stack->top];
return NULL;
}
void stack_pop_free(stack_t *stack, stack_deallocate func)
{
if (stack->top > 0)
func(stack->buf[--stack->top]);
}
void *stack_top(stack_t *stack)
{
if (stack->top > 0)
return stack->buf[stack->top-1];
return NULL;
}
void *stack_get(stack_t *stack, int i)
{
assert(i >= 0);
if (i < stack->size)
return stack->buf[i];
return NULL;
}
void stack_clear(stack_t *stack)
{
stack->size = 0;
stack->top = 0;
}
bool stack_empty(stack_t *stack)
{
return stack->top == 0;
}
int stack_size(stack_t *stack)
{
return stack->top;
}
void stack_free(stack_t *stack, stack_deallocate func)
{
if (func) {
for (int i = 0; i < stack->top; i++) {
func(stack->buf[i]);
}
}
free(stack->buf);
free(stack);
}