-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
84 lines (65 loc) · 1.61 KB
/
Copy pathstack.c
File metadata and controls
84 lines (65 loc) · 1.61 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "stack.h"
#include <stdlib.h>
stack_t *new_stack(size_t capacity) {
stack_t *stack = (stack_t *)malloc(sizeof(stack_t));
if (stack == NULL) {
return NULL;
}
stack->count = 0;
stack->capacity = capacity;
stack->data = malloc(sizeof(void *) * capacity);
if (stack->data == NULL) {
free(stack);
return NULL;
}
return stack;
}
void stack_push(stack_t *stack, void *value) {
if (stack->count == stack->capacity) {
stack->capacity *= 2;
stack->data = realloc(stack->data, sizeof(void *) * stack->capacity);
if (stack->data == NULL) {
stack->capacity /= 2;
return;
}
}
stack->data[stack->count] = value;
stack->count++;
}
void *stack_pop(stack_t *stack) {
if (stack->count == 0) {
return NULL;
}
stack->count--;
return stack->data[stack->count];
}
void free_stack(stack_t *stack) {
if (stack == NULL) {
return;
}
if (stack->data != NULL) {
free(stack->data);
}
free(stack);
}
void scary_double_push(stack_t *stack) {
stack_push(stack, (void *)1337);
int *ptr = (int *)malloc(sizeof(int));
*ptr = 42;
stack_push(stack, ptr);
}
void stack_remove_nulls(stack_t *stack) {
int new_count = 0;
// Update the count to reflect the new number of elements.
for (int i = 0; i < stack->count; i++) {
if (stack->data[i] != NULL) {
stack->data[new_count++] = stack->data[i];
}
}
// Update the count to reflect the new number of elements.
stack->count = new_count;
// Optionally, you might want to zero out the remaining slots.
for (int i = new_count; i < stack->capacity; i++) {
stack->data[i] = NULL;
}
}