-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
87 lines (78 loc) · 1.48 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
87
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
node *new_node(int32_t value) {
node *ret = (node *) malloc(sizeof(node));
ret->value = value;
ret->prev = NULL;
ret->next = NULL;
return ret;
}
void free_node(node *n)
{
free(n);
}
stack *new_stack()
{
stack *ret = (stack *) malloc(sizeof(stack));
ret->first = NULL;
ret->last = NULL;
ret->length = 0;
return ret;
}
void free_stack(stack *s)
{
if (s->length == 0)
{
free(s);
return;
}
node *current = s->first;
for (uint64_t i = 0; i < s->length; i++)
{
node *next = current->next;
free_node(current);
current = next;
}
}
void stack_push(stack *s, int value)
{
node *new = new_node(value);
if (s->length > 0)
{
new->prev = s->last;
s->last->next = new;
} else {
s->first = new;
}
s->length++;
s->last = new;
}
int32_t stack_pop(stack *s)
{
if (s->length == 0)
return 0;
int32_t last = s->last->value;
node *new_last = s->last->prev;
free_node(s->last);
s->length--;
s->last = new_last;
return last;
}
void stack_print(stack *s)
{
if (s->length == 0)
printf("[ ]\n");
else
{
printf("[");
node *current = s->first;
for (uint64_t i = 0; i < s->length; ++i)
{
printf(" %d", current->value);
current = current->next;
}
printf(" ]\n");
}
}