blob: 1014785beef7d4d599176c926e8929f9129fa459 (
plain) (
blame)
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
|
#include "./stack.h"
#include <stdbool.h>
#include <stdlib.h>
bool stack_is_empty(stack *s)
{
if (!s || s->top == -1) {
return true;
}
return false;
}
stack *new_stack(size_t size)
{
stack *s = malloc(sizeof(stack));
if (!s)
return NULL;
s->data = malloc(size * sizeof(void *));
if (!s->data) {
free(s);
return NULL;
}
s->capacity = size;
s->top = -1;
return s;
}
void free_stack(stack *s)
{
if (!s)
return;
free(s->data);
free(s);
}
void *pop(stack *s)
{
if (stack_is_empty(s))
return NULL;
return s->data[s->top--];
}
void *peek(stack *s)
{
if (stack_is_empty(s))
return NULL;
return s->data[s->top];
}
void *push(stack *s, void *data)
{
if (!s)
return NULL;
if (s->top + 1 >= s->capacity) {
s->capacity *= 2;
s->data = realloc(s->data, sizeof(void *) * s->capacity);
}
return s->data[++s->top] = data;
}
|