package Others;/* Program to reverse a Stack using Recursion*/import java.util.Stack;public class ReverseStackUsingRecursion {//Stackprivate static Stack<Integer> stack = new Stack<>();//Main functionpublic static void main(String[] args) {//To Create a Dummy Stack containing integers from 0-9for (int i = 0; i < 10; i++) {stack.push(i);}System.out.println("STACK");//To print that dummy Stackfor (int k = 9; k >= 0; k--) {System.out.println(k);}//Reverse Function calledreverseUsingRecursion(stack);System.out.println("REVERSED STACK : ");//To print reversed stackwhile (!stack.isEmpty()) {System.out.println(stack.pop());}}//Function Used to reverse Stack Using Recursionprivate static void reverseUsingRecursion(Stack<Integer> stack) {if (stack.isEmpty()) // If stack is empty then return{return;}/* All items are stored in call stack until we reach the end*/int temptop = stack.peek();stack.pop();reverseUsingRecursion(stack); //Recursion callinsertAtEnd(temptop); // Insert items held in call stack one by one into stack}//Function used to insert element at the end of stackprivate static void insertAtEnd(int temptop) {if (stack.isEmpty()) {stack.push(temptop); // If stack is empty push the element} else {int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/stack.pop();insertAtEnd(temptop); //Recursive callstack.push(temp);}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。