import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {

 public static <T> void reverseStack(Stack<T> stack) {
        if (stack.isEmpty()) {
            return;
        }
       
        T bottom = popBottom(stack);
        
       
        reverseStack(stack);
        
        
        stack.push(bottom);
    }
    private static <T> T popBottom(Stack<T> stack) {
        T top = stack.pop();
        if (stack.isEmpty()) {
          
            return top;
        } else {
           
            T bottom = popBottom(stack);
            
            stack.push(top);
            return bottom;
        }
    }

    private static <T> void printStack(Stack<T> stack){
        Iterator<T> iterator = stack.iterator();
        while (iterator.hasNext()) {
            T t = (T) iterator.next();
            System.out.print(" " + t);
        }
    }
    public static void main(String[] args) {
         Stack<Integer> stack = new Stack<>();
         stack.push(10);
         stack.push(20);
         stack.push(30);
         stack.push(40);
  
      
         printStack(stack);
         Main reversal = new Main();
         reversal.reverseStack(stack);
  
         
         printStack(stack);
  
         Stack<String> stack1 = new Stack<>();
         stack1.push("a");
         stack1.push("b");
         stack1.push("c");
         stack1.push("d");
         printStack(stack1);
         reversal.reverseStack(stack1);
         printStack(stack1);
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: