package com.thealgorithms.datastructures.stacks;
import java.util.Scanner;
import java.util.Stack;
public final class ReverseStack {
private ReverseStack() {
}
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter the number of elements you wish to insert in the stack");
int n = sc.nextInt();
int i;
Stack<Integer> stack = new Stack<Integer>();
System.out.println("Enter the stack elements");
for (i = 0; i < n; i++) {
stack.push(sc.nextInt());
}
reverseStack(stack);
System.out.println("The reversed stack is:");
while (!stack.isEmpty()) {
System.out.print(stack.peek() + ",");
stack.pop();
}
}
}
private static void reverseStack(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;
}
int element = stack.peek();
stack.pop();
reverseStack(stack);
insertAtBottom(stack, element);
}
private static void insertAtBottom(Stack<Integer> stack, int element) {
if (stack.isEmpty()) {
stack.push(element);
return;
}
int ele = stack.peek();
stack.pop();
insertAtBottom(stack, element);
stack.push(ele);
}
}