Reverse a Stack using Recursion

How to reverse a stack using Recursion? In this tutorial, I am going to discuss this interesting problem.

Given a stack of integers, we have to write a code to reverse them using recursion. For solving this problem, we don’t have to use any loop constructs (For, While etc.) or any additional data structure.

You can use stack methods like push, pop, isEmpty to solve this problem.

Reverse a stack using recursion

Programming Video Tutorials

Programming Questions on Stacks

If we have to use additional data structure then this problem would be easily solved by using another stack.

Reverse a Stack using Recursion – Java Code

Before solving this problem, let’s understand few important points.

We know in a stack the element which we pushed at last is the first element to be popped out. It follows Last In First Out (LIFO) order.

To reverse a stack, First we have to pop all the values of a stack recursively until the stack becomes empty. And then insert each values one by one at the bottom of the stack.

It means we have to use two recursive function to solve this problem. I have also shared the video tutorial at the end of this post.

The time complexity of this approach is O(n^2). And it’s space complexity is O(n).

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.