master
1#include "stack.h"
2#include <stdlib.h>
3
4Node *node_init(void *data) {
5 Node *node = malloc(sizeof(Node));
6 node->next = NULL;
7 node->data = data;
8 return node;
9}
10
11Stack *stack_init() {
12 Stack *stack = malloc(sizeof(Stack));
13 stack->head = NULL;
14 return stack;
15}
16
17int stack_size(Stack *self) {
18 if (!self || !self->head)
19 return 0;
20
21 int count = 0;
22 Node *current = self->head;
23 while (current) {
24 ++count;
25 current = current->next;
26 }
27
28 return count;
29}
30
31void *stack_peek(Stack *self) {
32 if (self->head)
33 return self->head->data;
34 return NULL;
35}
36
37void stack_push(Stack *stack, void *data) {
38 Node *node = node_init(data);
39 node->next = stack->head;
40 stack->head = node;
41}
42
43void *stack_pop(Stack *self) {
44 if (self->head) {
45 Node *tmp = self->head;
46 void *data = tmp->data;
47 self->head = self->head->next;
48 free(tmp);
49 return data;
50 }
51 return NULL;
52}