package DataStructures.Stacks;import java.util.Scanner;import java.util.Stack;/*** Reversal of a stack using recursion.** @author Ishika Agarwal, 2021*/public class ReverseStack {public static void main(String args[]){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());sc.close();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;}//Store the topmost elementint element = stack.peek();//Remove the topmost elementstack.pop();//Reverse the stack for the leftover elementsreverseStack(stack);//Insert the topmost element to the bottom of the stackinsertAtBottom(stack,element);}private static void insertAtBottom(Stack<Integer> stack, int element) {if(stack.isEmpty()){//When stack is empty, insert the element so it will be present at the bottom of the stackstack.push(element);return;}int ele = stack.peek();/*Keep popping elements till stack becomes empty. Push the elements once the topmost element hasmoved to the bottom of the stack.*/stack.pop();insertAtBottom(stack, element);stack.push(ele);}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。