-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack_example.c
More file actions
71 lines (60 loc) · 1.73 KB
/
stack_example.c
File metadata and controls
71 lines (60 loc) · 1.73 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
#include <stdio.h>
#include <stdlib.h>
#include "libdsc/stack.h"
int main() {
// Create a stack of integers
DSCStack *stack = stack_create(sizeof(int));
if (!stack) {
printf("Failed to create stack\n");
return EXIT_FAILURE;
}
// Push some values
int values[] = {1, 2, 3, 4, 5};
for (size_t i = 0; i < 5; ++i) {
if (stack_push(stack, &values[i]) != DSC_ERROR_OK) {
printf("Failed to push %d\n", values[i]);
continue;
}
printf("Pushed %d\n", values[i]);
}
// Print stack size
printf("\nStack size: %zu\n", stack_size(stack));
// Print top element
int *top = (int *)stack_top(stack);
if (top) {
printf("Top element: %d\n", *top);
}
// Pop and print all values
printf("\nPopping values:\n");
while (!stack_empty(stack)) {
top = (int *)stack_top(stack);
if (top) {
printf("Popping %d\n", *top);
}
stack_pop(stack);
}
// Try to pop from empty stack
printf("\nTrying to pop from empty stack: ");
if (stack_pop(stack) == DSC_ERROR_EMPTY) {
printf("Stack is empty (expected)\n");
}
// Push more values
printf("\nPushing more values:\n");
for (int i = 6; i <= 10; ++i) {
if (stack_push(stack, &i) == DSC_ERROR_OK) {
printf("Pushed %d\n", i);
}
}
// Reserve space
printf("\nReserving space for 100 elements: ");
if (stack_reserve(stack, 100) == DSC_ERROR_OK) {
printf("Success\n");
}
// Clear stack
printf("\nClearing stack\n");
stack_clear(stack);
printf("Stack size after clear: %zu\n", stack_size(stack));
// Clean up
stack_destroy(stack);
return EXIT_SUCCESS;
}