Example 1 — Reverse a string with a stack
Push each character, then pop them all.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *s = "hello";
char stack[16];
int top = -1;
for (size_t i = 0; i < strlen(s); i++) stack[++top] = s[i];
printf("reversed: ");
while (top >= 0) putchar(stack[top--]);
printf("\n");
return 0;
} How It Works
- Characters are pushed h, e, l, l, o.
- Popping returns o first and h last.
- The stack reversed the order automatically.
