]>
Commit | Line | Data |
---|---|---|
d104c687 MR |
1 | #include <stdlib.h> |
2 | #include "stack.h" | |
3 | ||
4 | typedef struct _Stack { | |
5 | void** elems; | |
6 | int size; | |
7 | } Stack; | |
8 | ||
9 | Stack* stack_init() { | |
10 | Stack* s = malloc(sizeof(Stack)); | |
11 | s->size = 0; | |
12 | s->elems = NULL; | |
13 | return s; | |
14 | } | |
15 | ||
16 | void* 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 | ||
27 | void 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 | ||
36 | void* stack_peek(Stack* stack) { | |
37 | if (stack_empty(stack)) | |
38 | return NULL; | |
39 | return stack->elems[stack->size - 1]; | |
40 | } | |
41 | ||
42 | bool stack_empty(Stack* stack) { | |
43 | return (stack == NULL || stack->size == 0); | |
44 | } | |
45 | ||
46 | void** 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 | } |