Last active
September 2, 2025 23:09
-
-
Save emyfops/0e4c1fb1b169f49a072aeb95a1c62514 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| typedef struct { | |
| int head; | |
| int item_size; | |
| int* items; | |
| } Stack; | |
| void | |
| initialize_stack(Stack* stack, const int size) | |
| { | |
| stack->head = -1; | |
| stack->item_size = size; | |
| stack->items = malloc(size * sizeof(*stack->items)); | |
| } | |
| void | |
| destroy_stack(Stack* stack) | |
| { | |
| free(stack->items); | |
| stack->items = NULL; | |
| } | |
| void | |
| _grow(Stack* stack) | |
| { | |
| stack->item_size *= 2; | |
| int* new_stack = realloc(stack->items, stack->item_size * sizeof(*stack->items)); | |
| if (new_stack == NULL) | |
| fprintf(stderr, "Could not grow the stack"); | |
| else | |
| stack->items = new_stack; | |
| } | |
| void | |
| push(Stack* stack, const int value) | |
| { | |
| if (stack->head+1 == stack->item_size) _grow(stack); | |
| stack->items[ | |
| ++stack->head] = value; | |
| } | |
| int | |
| pop(Stack* stack) | |
| { | |
| assert(stack->head > -1); | |
| return stack->items[stack->head--]; | |
| } | |
| int | |
| main(const int argc, char** argv) | |
| { | |
| Stack s; | |
| initialize_stack(&s, 4); | |
| push(&s, 1); | |
| push(&s, 2); | |
| push(&s, 3); | |
| push(&s, 4); | |
| push(&s, 5); | |
| push(&s, 6); | |
| push(&s, 7); | |
| push(&s, 8); | |
| printf("1: %d\n", pop(&s)); | |
| printf("2: %d\n", pop(&s)); | |
| printf("3: %d\n", pop(&s)); | |
| printf("4: %d\n", pop(&s)); | |
| printf("5: %d\n", pop(&s)); | |
| printf("6: %d\n", pop(&s)); | |
| printf("7: %d\n", pop(&s)); | |
| printf("8: %d\n", pop(&s)); | |
| destroy_stack(&s); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment