Horje
Reversing a Stack using two empty Stacks

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

Python3

# Python3 program for the above approach
 
# Function to display the
# contents of the stack S
def display(S):
   
    # Iterate while S is
    # not empty
    while len(S) > 0:
 
        # Print the top
        # element of the stack S
        print(S[-1], end = " ")
 
        # Pop from S
        S.pop()
    print()
 
# Function to reverse a stack using two stacks
def reverseStackUsingTwoStacks(S):
   
    # Two additional stacks
    A = []
    B = []
        
    # Transfer all elements
    # from the stack S to A
    while len(S) > 0:
        A.append(S[-1])
        S.pop()
        
    # Transfer all elements
    # from the stack A to B
    while len(A) > 0:
        B.append(A[-1])
        A.pop()
        
    # Transfer all elements
    # from the stack B to S
    while len(B) > 0:
        S.append(B[-1])
        B.pop()
        
    # Print the contents of S
    display(S)
 
# Given Input
# Input
S = []
S.append(5)
S.append(4)
S.append(3)
S.append(2)
S.append(1)
 
# Function call
reverseStackUsingTwoStacks(S)
 
# This code is contributed by suresh07.

C#

// C# program for the above approach
using System;
using System.Collections;
class GFG {
     
    // Function to transfer elements
    // from the stack X to the stack Y
    static void transfer(Stack X, Stack Y)
    {
        // Iterate while X is not empty
        while (X.Count > 0)
        {
  
            // 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 S)
    {
        // Iterate while S is
        // not empty
        while (S.Count > 0) {
  
            // Print the top
            // element of the stack S
            Console.Write(S.Peek() + " ");
  
            // Pop from S
            S.Pop();
        }
        Console.WriteLine();
    }
  
    // Function to reverse a stack using two stacks
    static void reverseStackUsingTwoStacks(Stack S)
    {
        // Two additional stacks
        Stack A = new Stack();
        Stack B = new Stack();
  
        // Transfer all elements
        // from the stack S to A
        while (S.Count > 0)
            A.Push(S.Pop());
  
        // Transfer all elements
        // from the stack A to B
        while (A.Count > 0)
            B.Push(A.Pop());
  
        // Transfer all elements
        // from the stack B to S
        while (B.Count > 0)
            S.Push(B.Pop());
  
        // Print the contents of S
        display(S);
    }
 
  static void Main() {
    // Given Input
    // Input
    Stack 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 divyesh072019.

Javascript

<script>
    // Javascript program for the above approach
   
    // Function to display the
    // contents of the stack S
    function display(S)
    {
        // Iterate while S is
        // not empty
        while (S.length > 0) {
   
            // Print the top
            // element of the stack S
            document.write(S[S.length - 1] + " ");
   
            // Pop from S
            S.pop();
        }
        document.write("</br>");
    }
   
    // Function to reverse a stack using two stacks
    function reverseStackUsingTwoStacks(S)
    {
        // Two additional stacks
        let A = [];
        let B = [];
           
        // Transfer all elements
        // from the stack S to A
        while (S.length > 0)
        {
            A.push(S[S.length - 1]);
            S.pop();
        }
           
        // Transfer all elements
        // from the stack A to B
        while (A.length > 0)
        {
            B.push(A[A.length - 1]);
            A.pop();
        }
           
        // Transfer all elements
        // from the stack B to S
        while (B.length > 0)
        {
            S.push(B[B.length - 1]);
            B.pop();
        }
           
        // Print the contents of S
        display(S);
    }
     
    // Given Input
    // Input
    let S = [];
    S.push(5);
    S.push(4);
    S.push(3);
    S.push(2);
    S.push(1);
  
    // Function call
    reverseStackUsingTwoStacks(S);
     
    // This code is contributed by mukesh07.
</script>

 
 

Output: 

5 4 3 2 1

 

 

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

 




Reffered: https://www.geeksforgeeks.org


DSA

Related
Smallest number required to be added to M to make it divisible by N Smallest number required to be added to M to make it divisible by N
Calculate money placed in boxes after N days based on given conditions Calculate money placed in boxes after N days based on given conditions
Reduced Row Echelon Form (rref) Matrix in MATLAB Reduced Row Echelon Form (rref) Matrix in MATLAB
Recently Asked Interview Questions in Product Based Companies Recently Asked Interview Questions in Product Based Companies
Number of relations that are neither Reflexive nor Irreflexive on a Set Number of relations that are neither Reflexive nor Irreflexive on a Set

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10