-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
60 lines (54 loc) · 990 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
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "stack.h"
#include <assert.h>
#include <stddef.h>
#include "mem.h"
#include <stdint.h>
#define T Stack_T
struct T{
int32_t count;
struct elem{
void *x;
struct elem *link;
}*head;
};
T Stack_new(void){
T stk;
NEW(stk);
stk->count = 0;
stk->head = NULL;
return stk;
}
int32_t Stack_empty(T stk){
assert(stk);
return stk->count == 0;
}
void Stack_push(T stk, void *x){
struct elem *t;
assert(stk);
NEW(t);
t->x=x;
t->link = stk->head;
stk->head=t;
stk->count++;
}
void *Stack_pop(T stk){
void *x;
struct elem *t;
assert(stk);
assert(stk->count>0);
t=stk->head;
stk->head = t->link;
stk->count--;
x=t->x;
FREE(t);
return x;
}
void Stack_free(T *stk){
struct elem *t, *u;
assert(stk && *stk);
for(t = (*stk)->head; t; t=u){
u=t->link;
FREE(t);
}
FREE(*stk);
}