Update appNew update is available. Click here to update.

Reverse Stack Using Recursion

Contributed by
Ashwani
Last Updated: 23 Feb, 2023
Easy
yellow-spark
0/40
Avg time to solve 21 mins
Success Rate 80 %
Share
159 upvotes

Problem Statement

Reverse a given stack of integers using recursion.

Note:

You are not allowed to use any extra space other than the internal stack space used due to recursion.
You are not allowed to use the loop constructs of any sort available as handy. For example: for, for-each, while, etc. 
The only inbuilt stack methods allowed are:
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
Detailed explanation ( Input/output format, Notes, Images )
Constraints :
0 <= N <= 10^3

Where 'N' is the number of elements in the given stack.

Time Limit: 1 sec
Output Format :
N single space-separated integers in a single line, where the first integer denotes the TOP element of the reversed stack.
Sample Input 1 :
3
2 1 3
Sample Output 1 :
2 1 3
Explanation to Sample Input 1 :
First-line contains an integer 3 denotes the size of the input stack i.e N = 3.
Second-line contains 3 single space-separated integers i.e the elements of the stack.

alt text

Printing the reverse stack starting from the top element: 2 1 3.                    
Sample Input 2 :
2
3 2
Sample Output 2 :
3 2    
Reset Code
Full screen
Auto
copy-code
Console