Skip to content
Related Articles

Related Articles

Improve Article

Reversing a Stack using two empty Stacks

  • Last Updated : 09 Jun, 2021

Given a stack S, the task is to reverse the stack S using two additional stacks.

Example:

Input: S={1, 2, 3, 4, 5}
Output: 5 4 3 2 1
Explanation:
The initial stack S:
1→top
2
3
4
5
After reversing it, use two additional stacks:
5→top
4
3
2
1

Input: S={1, 25, 17}
Output: 17 25 1

 

Approach: Follow the steps below to solve the problem:



  1. Create two additional empty stacks, say A and B.
  2. Define a function transfer() that accepts two stacks X and Y as parameters and performs the following operations:
    1. Loop while X is not empty and perform the following operations:
      1. Push the top element of the stack X into Y.
      2. Pop that element from X.
  3. Call transfer(S, A) tos transfers all elements of the stack S to A. (The order of the elements is reversed).
  4. Call transfer(A, B) to transfer all elements of the stack A to B. (The order of the elements is the same as initially in S)
  5. Call transfer(B, S) to transfer all elements of B to S. (The order of the elements is reversed)
  6. Finally, display the stack S.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to transfer elements
// from the stack X to the stack Y
void transfer(stack<int>& X,
              stack<int>& Y)
{
    // Iterate while X is not empty
    while (!X.empty()) {
 
        // Push the top element
        // of X into Y
        Y.push(X.top());
 
        // Pop from X
        X.pop();
    }
}
 
// Function to display the
// contents of the stack S
void display(stack<int> S)
{
    // Iterate while S is
    // not empty
    while (!S.empty()) {
 
        // Print the top
        // element of the stack S
        cout << S.top() << " ";
 
        // Pop from S
        S.pop();
    }
    cout << endl;
}
 
// Function to reverse a stack using two stacks
void reverseStackUsingTwoStacks(stack<int>& S)
{
    // Two additional stacks
    stack<int> A, B;
 
    // Transfer all elements
    // from the stack S to A
    transfer(S, A);
 
    // Transfer all elements
    // from the stack A to B
    transfer(A, B);
 
    // Transfer all elements
    // from the stack B to S
    transfer(B, S);
 
    // Print the contents of S
    display(S);
}
// Driver Code
int main()
{
    // Input
    stack<int> S;
    S.push(5);
    S.push(4);
    S.push(3);
    S.push(2);
    S.push(1);
 
    // Function call
    reverseStackUsingTwoStacks(S);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.Stack;
public class GFG
{
 
    // Function to transfer elements
    // from the stack X to the stack Y
    static void transfer(Stack<Integer> X, Stack<Integer> Y)
    {
        // Iterate while X is not empty
        while (!X.empty())
        {
 
            // Push the top element
            // of X into Y
            Y.push(X.peek());
 
            // Pop from X
            X.pop();
        }
    }
 
    // Function to display the
    // contents of the stack S
    static void display(Stack<Integer> S)
    {
        // Iterate while S is
        // not empty
        while (!S.empty()) {
 
            // Print the top
            // element of the stack S
            System.out.print(S.peek() + " ");
 
            // Pop from S
            S.pop();
        }
        System.out.println();
    }
 
    // Function to reverse a stack using two stacks
    static void reverseStackUsingTwoStacks(Stack<Integer> S)
    {
        // Two additional stacks
        Stack<Integer> A = new Stack<>();
        Stack<Integer> B = new Stack<>();
 
        // Transfer all elements
        // from the stack S to A
        while (!S.empty())
            A.push(S.pop());
 
        // Transfer all elements
        // from the stack A to B
        while (!A.empty())
            B.push(A.pop());
 
        // Transfer all elements
        // from the stack B to S
        while (!B.empty())
            S.push(B.pop());
 
        // Print the contents of S
        display(S);
    }
 
    // Driver code
    public static void main(String[] args)
    {
       
      // Given Input
      // Input
        Stack<Integer> S = new Stack<>();
        S.push(5);
        S.push(4);
        S.push(3);
        S.push(2);
        S.push(1);
 
        // Function call
        reverseStackUsingTwoStacks(S);
    }
}
 
// This code is contributed by abhinavjain194

 
 

Output: 
5 4 3 2 1

 

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :