Given a stack, recursively reverse it only using its abstract data type (ADT) standard operations, i.e., push(item), pop(), peek(), isEmpty(), size(), etc.

The idea is to hold all items in a call stack until the stack becomes empty. Then, insert each item in the call stack at the bottom of the stack. Following is the pictorial representation of the above logic:

Pop elements from input stack

 
Stack – Pop from Call Stack

Practice this problem

To insert an item x at the bottom of the given stack, pop all items from the stack and hold them in the call stack. When the stack becomes empty, push the given item x into the stack. Then as the recursion unfolds, push each item in the call stack into the stack’s top.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

Reversed stack is 1 2 3 4 5

Java


Download  Run Code

Output:

Original stack is [1, 2, 3, 4, 5]
Reversed stack is [5, 4, 3, 2, 1]

Python


Download  Run Code

Output:

Original stack is deque([1, 2, 3, 4, 5])
Reversed stack is deque([5, 4, 3, 2, 1])

The time complexity of the above solution is O(n2) and requires O(n) implicit space for the call stack, where n is the total number of elements in the stack. The recurrence relation is:

T(n) = T(n-1) + n
    = T(n-2) + (n-1) + n
    = T(n-3) + (n-2) + (n-1) + n
 
and so on, until
 
T(n) = T(n-(n-1)) + T(n-(n-2)) + … + (n-2) + (n-1) + n
    = T(1) + T(2) + … + (n-2) + (n-1) + n = n×(n+1)/2
    = 1 + 2 + … + (n-2) + (n-1) + n = n×(n+1)/2
    = O(n2)