-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack.c
More file actions
79 lines (66 loc) · 1.57 KB
/
stack.c
File metadata and controls
79 lines (66 loc) · 1.57 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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_INIT_CAP 256
typedef struct stack {
size_t count;
size_t capacity;
int* items;
} stack_T;
stack_T* stack_alloc()
{
stack_T* stack = malloc(sizeof(stack_T));
stack->count = 0;
stack->capacity = STACK_INIT_CAP;
stack->items = malloc(sizeof(int) * stack->capacity);
return stack;
}
void stack_free(stack_T* stack)
{
free(stack->items);
free(stack);
}
void stack_print(stack_T* stack)
{
for (size_t i = 0; i < stack->count; i++)
{
printf("%d ", stack->items[i]);
}
printf("\n");
}
void stack_push(stack_T* stack, int item)
{
if (stack->count == stack->capacity)
{
stack->capacity *= 2;
stack->items = realloc(stack->items, stack->capacity * sizeof(int));
}
stack->items[stack->count++] = item;
}
bool stack_is_empty(stack_T* stack)
{
return stack->count == 0;
}
int stack_pop(stack_T* stack)
{
if (stack_is_empty(stack))
{
fprintf(stderr, "Can't pop from an empty stack!\n");
return -1;
}
return stack->items[--stack->count];
}
int main()
{
stack_T* stack = stack_alloc();
for (size_t i = 0; i < 10; i++) stack_push(stack, i);
stack_print(stack);
int last = stack_pop(stack);
printf("Last item: %d\n", last);
stack_print(stack);
int first;
while (!stack_is_empty(stack)) first = stack_pop(stack);
printf("First item: %d\n", first);
stack_free(stack);
return 0;
}