blob: ba3655d967d5306e47b50300b82239ce87d7fa4d (
plain)
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
|
#include "stack.h"
#include <stdlib.h>
Node *node_init(void *data) {
Node *node = malloc(sizeof(Node));
node->next = NULL;
node->data = data;
return node;
}
Stack *stack_init() {
Stack *stack = malloc(sizeof(Stack));
stack->head = NULL;
return stack;
}
int stack_size(Stack *self) {
if (!self || !self->head)
return 0;
int count = 0;
Node *current = self->head;
while (current) {
++count;
current = current->next;
}
return count;
}
void *stack_peek(Stack *self) {
if (self->head)
return self->head->data;
return NULL;
}
void stack_push(Stack *stack, void *data) {
Node *node = node_init(data);
node->next = stack->head;
stack->head = node;
}
void *stack_pop(Stack *self) {
if (self->head) {
Node *tmp = self->head;
void *data = tmp->data;
self->head = self->head->next;
free(tmp);
return data;
}
return NULL;
}
|