Home » Reverse a stack using recursion

Reverse a stack using recursion

by Online Tutorials Library

Reverse a stack using recursion

Here, we are going to reverse a stack using recursion. We are not supposed to use any loop constructs like for loop, while loop, do-while loop, etc. We should use the recursion method to reverse a stack.

For example: input: s = [10, 20, 30, 40, 50]

Output: [50, 40, 30, 20, 10]

Explanation: When the stack s is reversed then the output would be [50, 40, 30, 20, 10].

There are various ways to reverse a stack using recursion. The most common way of reversing a stack is to use an auxiliary stack. First, we will pop all the elements from the stack and push them into the auxiliary stack. Once all the elements are pushed into the auxiliary stack, then it contains the elements in the reverse order and we simply print them. But, here, we will not use the auxiliary stack. We will use a recursion method to reverse a stack where recursion means calling the function itself again and again.

In the recursion method, we first pop all the elements from the input stack and push all the popped items into the function call stack until the stack becomes empty. When the stack becomes empty, all the items will be pushed at the stack. Let’s understand this scenario through an example.

For example:

Input stack: 1, 2, 3, 4, 5

Reverse a stack using recursion

Output: 5, 4, 3, 2, 1

Solution: Firstly, all the elements from the input stack are pushed into the function call stack

Step 1: Element 5 is pushed at the bottom of the stack shown as below:

Reverse a stack using recursion

Step 2: Element 4 is pushed at the bottom of the stack shown as below:

Reverse a stack using recursion

Step 3: Element 3 is pushed at the bottom of the stack shown as below:

Reverse a stack using recursion

Step 4: Element 2 is pushed at the bottom of the stack shown as below:

Reverse a stack using recursion

Step 5: Element 1 is pushed at the bottom of the stack shown as below:

Reverse a stack using recursion

Implementation in C

Output

Reverse a stack using recursion


You may also like