🔄🔥Advanced
Reverse a Stack Using Recursion
Reverse stack recursively
Reverse a stack using recursion without using any extra stack.
Program Code
reverse_stack_recursion.c
C
1#include <stdio.h>2#define MAX 10034int stack[MAX];5int top = -1;67void push(int item) {8 if (top < MAX - 1) {9 stack[++top] = item;10 }11}1213int pop() {14 if (top >= 0) {15 return stack[top--];16 }17 return -1;18}1920int isEmpty() {21 return top == -1;22}2324// Insert at bottom recursively25void insertAtBottom(int item) {26 if (isEmpty()) {27 push(item);28 } else {29 int temp = pop();30 insertAtBottom(item);31 push(temp);32 }33}3435// Reverse stack using recursion36void reverseStack() {37 if (!isEmpty()) {38 int temp = pop();39 reverseStack();40 insertAtBottom(temp);41 }42}4344void printStack() {45 printf("Stack (top to bottom): ");46 for (int i = top; i >= 0; i--) {47 printf("%d ", stack[i]);48 }49 printf("\n");50}5152int main() {53 push(1);54 push(2);55 push(3);56 push(4);57 push(5);58 59 printf("Original ");60 printStack();61 62 reverseStack();63 64 printf("Reversed ");65 printStack();66 67 return 0;68}Output
Original Stack (top to bottom): 5 4 3 2 1
Reversed Stack (top to bottom): 1 2 3 4 5
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials