|
| 1 | +/* Program to reverse a Stack using Recursion*/ |
| 2 | + |
| 3 | + |
| 4 | +import java.util.Stack; |
| 5 | + |
| 6 | +public class ReverseStackUsingRecursion { |
| 7 | + |
| 8 | + //Stack |
| 9 | + private static Stack<Integer> stack=new Stack<>(); |
| 10 | + |
| 11 | + //Main function |
| 12 | + public static void main(String[] args) { |
| 13 | + //To Create a Dummy Stack containing integers from 0-9 |
| 14 | + for(int i=0;i<10;i++) |
| 15 | + { |
| 16 | + stack.push(i); |
| 17 | + } |
| 18 | + System.out.println("STACK"); |
| 19 | + |
| 20 | + //To print that dummy Stack |
| 21 | + for(int k=9;k>=0;k--) |
| 22 | + { |
| 23 | + System.out.println(k); |
| 24 | + } |
| 25 | + |
| 26 | + //Reverse Function called |
| 27 | + reverseUsingRecursion(stack); |
| 28 | + |
| 29 | + System.out.println("REVERSED STACK : "); |
| 30 | + //To print reversed stack |
| 31 | + while (!stack.isEmpty()) |
| 32 | + { |
| 33 | + System.out.println(stack.pop()); |
| 34 | + } |
| 35 | + |
| 36 | + |
| 37 | + } |
| 38 | + |
| 39 | + //Function Used to reverse Stack Using Recursion |
| 40 | + private static void reverseUsingRecursion(Stack<Integer> stack) { |
| 41 | + if(stack.isEmpty()) // If stack is empty then return |
| 42 | + { |
| 43 | + return; |
| 44 | + } |
| 45 | + /* All items are stored in call stack until we reach the end*/ |
| 46 | + |
| 47 | + int temptop=stack.peek(); |
| 48 | + stack.pop(); |
| 49 | + reverseUsingRecursion(stack); //Recursion call |
| 50 | + insertAtEnd(temptop); // Insert items held in call stack one by one into stack |
| 51 | + } |
| 52 | + |
| 53 | + //Function used to insert element at the end of stack |
| 54 | + private static void insertAtEnd(int temptop) { |
| 55 | + if(stack.isEmpty()) |
| 56 | + { |
| 57 | + stack.push(temptop); // If stack is empty push the element |
| 58 | + } |
| 59 | + else { |
| 60 | + int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/ |
| 61 | + stack.pop(); |
| 62 | + |
| 63 | + insertAtEnd(temptop); //Recursive call |
| 64 | + |
| 65 | + stack.push(temp); |
| 66 | + } |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | +} |
0 commit comments