DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS
Reverse a Stack Using Recursion
Learn how to reverse a stack using recursion using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
10 20 30
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
#define CAPACITY 50
struct Stack { int values[CAPACITY]; int top; };
void stack_init(struct Stack *stack) { stack->top = -1; }
int stack_empty(const struct Stack *stack) { return stack->top < 0; }
void stack_push(struct Stack *stack, int value)
{
if (stack->top + 1 >= CAPACITY) { puts("Stack overflow."); exit(EXIT_FAILURE); }
stack->values[++stack->top] = value;
}
int stack_pop(struct Stack *stack)
{
if (stack_empty(stack)) { puts("Stack underflow."); exit(EXIT_FAILURE); }
return stack->values[stack->top--];
}
int stack_peek(const struct Stack *stack)
{
if (stack_empty(stack)) { puts("Stack is empty."); exit(EXIT_FAILURE); }
return stack->values[stack->top];
}
void insert_bottom(struct Stack *stack, int value)
{
if (stack_empty(stack)) { stack_push(stack, value); return; }
int top = stack_pop(stack);
insert_bottom(stack, value);
stack_push(stack, top);
}
void reverse_stack(struct Stack *stack)
{
if (stack_empty(stack)) return;
int top = stack_pop(stack);
reverse_stack(stack);
insert_bottom(stack, top);
}
int main(void)
{
struct Stack stack; stack_init(&stack);
stack_push(&stack, 10); stack_push(&stack, 20); stack_push(&stack, 30);
reverse_stack(&stack);
while (!stack_empty(&stack)) printf("%d ", stack_pop(&stack));
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
10 20 30
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Recursively remove each top value and insert it beneath all remaining values.
- Display the computed result.
Recursively remove each top value and insert it beneath all remaining values.
EFFICIENCY
Time and space complexity
Time complexity
O(n²)
Auxiliary space
O(n) call stack
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
