]>
git.datanom.net - clib.git/blob - src/stack.c
12 static void free_elem(Stack
* stack
) {
14 for (int i
= 0; i
< stack
->size
; i
++)
15 stack
->free(stack
->elems
[i
]);
20 static Stack
* stack_new_common() {
21 Stack
* s
= malloc(sizeof(Stack
));
22 s
->elems
= malloc(sizeof(void*) * INIT_SIZE
);
29 return stack_new_common();
32 Stack
* stack_new_full(StackFreeFunc free
) {
33 Stack
* s
= stack_new_common();
38 void stack_destroy(Stack
* stack
) {
43 void* stack_pop(Stack
* stack
) {
44 if (stack_empty(stack
))
47 void* elem
= stack
->elems
[stack
->size
];
48 stack
->elems
[stack
->size
] = NULL
;
53 void stack_push(Stack
* stack
, void* elem
) {
58 if (stack
->size
== INIT_SIZE
) {
59 stack
->elems
= realloc(stack
->elems
, (INIT_SIZE
+ stack
->size
) * sizeof(void*));
62 stack
->elems
[stack
->size
- 1] = elem
;
65 void* stack_peek(Stack
* stack
) {
66 if (stack_empty(stack
))
68 return stack
->elems
[stack
->size
- 1];
71 bool stack_empty(Stack
* stack
) {
72 return (stack
== NULL
|| stack
->size
== 0);
75 void stack_clear(Stack
* stack
) {
83 int stack_size(Stack
* stack
) {
84 if (stack_empty(stack
))
90 typedef struct _Stack {
96 static void free_elem(Stack* stack) {
98 for (int i = 0; i < stack->size; i++)
99 stack->free(stack->elems[i]);
105 Stack* s = malloc(sizeof(Stack));
112 Stack* stack_new_full(StackFreeFunc free) {
113 Stack* s = malloc(sizeof(Stack));
120 void stack_destroy(Stack* stack) {
125 void* stack_pop(Stack* stack) {
126 if (stack_empty(stack))
129 void* elem = stack->elems[stack->size];
130 stack->elems[stack->size] = NULL;
131 stack->elems = realloc(stack->elems, stack->size * sizeof(void*));
136 void stack_push(Stack* stack, void* elem) {
141 stack->elems = realloc(stack->elems, stack->size * sizeof(void*));
142 stack->elems[stack->size - 1] = elem;
145 void* stack_peek(Stack* stack) {
146 if (stack_empty(stack))
148 return stack->elems[stack->size - 1];
151 bool stack_empty(Stack* stack) {
152 return (stack == NULL || stack->size == 0);
155 void stack_clear(Stack* stack) {
164 int stack_size(Stack* stack) {
165 if (stack_empty(stack))
This page took 0.126078 seconds and 6 git commands to generate.