Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack.
Examples:
Input: stack = {1, 2, 3, 4, 5}
Output:
1
2
3
4
5
Explanation:
Input Stack:
5
4
3
2
1
Reversed Stack:
1
2
3
4
5Input: stack = {1, 3, 5, 4, 2}
Output:
1
3
5
4
2
Approach: Follow the steps below to solve the problem:
- Initialize an empty stack.
- Pop the top element of the given stack S and store it in a temporary variable.
- Transfer all the elements of the given stack to the stack initialized above.
- Push the temporary variable into the original stack.
- Transfer all the elements present in the new stack into the original stack.
Below is the implementation of the above approach.
C++
// C++ program to reverse a stack// by using an extra stack#include <bits/stdc++.h>using namespace std; // Function to transfer elements of// the stack s1 to the stack s2void transfer(stack<int>& s1, stack<int>& s2, int n){ for (int i = 0; i < n; i++) { // Store the top element // in a temporary variable int temp = s1.top(); // Pop out of the stack s1.pop(); // Push it into s2 s2.push(temp); }} // Function to reverse a stack using another stackvoid reverse_stack_by_using_extra_stack(stack<int>& s, int n){ stack<int> s2; for (int i = 0; i < n; i++) { // Store the top element // of the given stack int x = s.top(); // Pop that element // out of the stack s.pop(); transfer(s, s2, n - i - 1); s.push(x); transfer(s2, s, n - i - 1); }} // Driver Codeint main(){ int n = 5; stack<int> s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); reverse_stack_by_using_extra_stack(s, n); for (int i = 0; i < n; i++) { cout << s.top() << " "; s.pop(); } return 0;} |
1 2 3 4 5
Time Complexity: O(N2)
Auxiliary Space: O(N)

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.

