]> git.datanom.net - clib.git/blame_incremental - stack.c
init
[clib.git] / stack.c
... / ...
CommitLineData
1#include <stdlib.h>
2#include "stack.h"
3
4typedef struct _Stack {
5 void** elems;
6 int size;
7} Stack;
8
9Stack* stack_init() {
10 Stack* s = malloc(sizeof(Stack));
11 s->size = 0;
12 s->elems = NULL;
13 return s;
14}
15
16void* stack_pop(Stack* stack) {
17 if (stack_empty(stack))
18 return NULL;
19 stack->size -= 1;
20 void* elem = stack->elems[stack->size];
21 stack->elems[stack->size] = NULL;
22 stack->elems = realloc(stack->elems, stack->size * sizeof(void*));
23
24 return elem;
25}
26
27void stack_push(Stack* stack, void* elem) {
28 if (stack == NULL)
29 return;
30
31 stack->size += 1;
32 stack->elems = realloc(stack->elems, stack->size * sizeof(void*));
33 stack->elems[stack->size - 1] = elem;
34}
35
36void* stack_peek(Stack* stack) {
37 if (stack_empty(stack))
38 return NULL;
39 return stack->elems[stack->size - 1];
40}
41
42bool stack_empty(Stack* stack) {
43 return (stack == NULL || stack->size == 0);
44}
45
46void** stack_clear(Stack** stack) {
47 if (*stack == NULL)
48 return NULL;
49 void** elems = (*stack)->elems;
50 free(*stack);
51 *stack = NULL;
52 return elems;
53}
This page took 0.051047 seconds and 5 git commands to generate.