DynamicStack stack; initStack(&stack); push(&stack, 10); push(&stack, 20); push(&stack, 30); push(&stack, 40); printStack(&stack);
The stack pushes elements in order: 10, 20, 30, 40. The top is the last pushed element, 40. So the stack from top to bottom is 40, 30, 20, 10.
DynamicStack stack; initStack(&stack); push(&stack, 5); push(&stack, 15); push(&stack, 25); pop(&stack); push(&stack, 35); int size = stackSize(&stack); printf("%d", size);
Push 5, 15, 25 → size 3. Pop removes top (25) → size 2. Push 35 → size 3.
int pop(DynamicStack *stack) { if (stack->top == -1) { printf("Stack Underflow\n"); return -1; } int value = stack->array[stack->top]; stack->top--; if (stack->top < stack->capacity / 4) { stack->capacity /= 2; stack->array = realloc(stack->array, stack->capacity * sizeof(int)); } return value; }
If realloc fails, it returns NULL but the original memory is not freed. Assigning directly to stack->array without checking causes memory leak or invalid access.
Doubling capacity reduces the frequency of resizing, so push operations have amortized O(1) time. Fixed increments cause frequent resizing and higher total cost.
DynamicStack stack; initStack(&stack); push(&stack, 1); push(&stack, 2); push(&stack, 3); pop(&stack); pop(&stack); push(&stack, 4); push(&stack, 5); pop(&stack); printStack(&stack);
Push 1,2,3 → stack top:3,2,1. Pop removes 3, then pop removes 2 → stack top:1. Push 4,5 → stack top:5,4,1. Pop removes 5 → stack top:4,1.
