-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.txt
More file actions
97 lines (78 loc) · 1.56 KB
/
stack.txt
File metadata and controls
97 lines (78 loc) · 1.56 KB
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
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include "stack_{{suffix}}.h"
typedef struct node node_t;
struct node {
{{type}} data;
node_t *next;
};
struct stack {
node_t *top;
clone_fn clone;
free_fn free;
};
stack_t * stack_new(stack_params_t params)
{
stack_t *s = malloc(sizeof(stack_t));
if (!s) {
return s;
}
s->top = NULL;
s->clone = params.clone;
s->free = params.free;
return s;
}
void stack_free(void *self)
{
free_fn fn = ((stack_t *) self)->free;
node_t *p = ((stack_t *) self)->top;
node_t *temp;
while (p) {
temp = p;
p = p->next;
if (fn) {
fn((void *) temp->data);
}
free((void *) temp);
}
free(self);
}
{{type}} stack_peek(stack_t *self)
{
assert(self);
if (self->clone) {
return self->clone((void *) self->top->data);
}
return self->top->data;
}
bool stack_push(stack_t *self, {{type}} data)
{
assert(self);
node_t *n = malloc(sizeof(node_t));
if (!n) {
return false;
}
n->data = data;
n->next = self->top;
self->top = n;
return true;
}
{{type}} stack_pop(stack_t *self)
{
assert(self && self->top);
{{type}} out;
if (self->clone) {
out = self->clone((void *) self->top->data);
}
else {
out = self->top->data;
}
node_t *p = self->top;
self->top = self->top->next;
if (self->free) {
self->free((void *) p->data);
}
free(p);
return out;
}