2019-05-09 19:32:54 +08:00
|
|
|
package Others;
|
|
|
|
|
2017-10-01 15:15:13 +08:00
|
|
|
/* Program to reverse a Stack using Recursion*/
|
2017-10-01 15:09:38 +08:00
|
|
|
|
|
|
|
|
|
|
|
import java.util.Stack;
|
|
|
|
|
|
|
|
public class ReverseStackUsingRecursion {
|
|
|
|
|
|
|
|
//Stack
|
2019-05-09 19:32:54 +08:00
|
|
|
private static Stack<Integer> stack = new Stack<>();
|
2017-10-01 15:09:38 +08:00
|
|
|
|
|
|
|
//Main function
|
|
|
|
public static void main(String[] args) {
|
|
|
|
//To Create a Dummy Stack containing integers from 0-9
|
2019-05-09 19:32:54 +08:00
|
|
|
for (int i = 0; i < 10; i++) {
|
2017-10-01 15:09:38 +08:00
|
|
|
stack.push(i);
|
|
|
|
}
|
|
|
|
System.out.println("STACK");
|
|
|
|
|
|
|
|
//To print that dummy Stack
|
2019-05-09 19:32:54 +08:00
|
|
|
for (int k = 9; k >= 0; k--) {
|
2017-10-01 15:09:38 +08:00
|
|
|
System.out.println(k);
|
|
|
|
}
|
|
|
|
|
|
|
|
//Reverse Function called
|
|
|
|
reverseUsingRecursion(stack);
|
|
|
|
|
|
|
|
System.out.println("REVERSED STACK : ");
|
|
|
|
//To print reversed stack
|
2019-05-09 19:32:54 +08:00
|
|
|
while (!stack.isEmpty()) {
|
2017-10-01 15:09:38 +08:00
|
|
|
System.out.println(stack.pop());
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
//Function Used to reverse Stack Using Recursion
|
|
|
|
private static void reverseUsingRecursion(Stack<Integer> stack) {
|
2019-05-09 19:32:54 +08:00
|
|
|
if (stack.isEmpty()) // If stack is empty then return
|
2017-10-01 15:09:38 +08:00
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
/* All items are stored in call stack until we reach the end*/
|
|
|
|
|
2019-05-09 19:32:54 +08:00
|
|
|
int temptop = stack.peek();
|
2017-10-01 15:09:38 +08:00
|
|
|
stack.pop();
|
|
|
|
reverseUsingRecursion(stack); //Recursion call
|
|
|
|
insertAtEnd(temptop); // Insert items held in call stack one by one into stack
|
|
|
|
}
|
|
|
|
|
|
|
|
//Function used to insert element at the end of stack
|
|
|
|
private static void insertAtEnd(int temptop) {
|
2019-05-09 19:32:54 +08:00
|
|
|
if (stack.isEmpty()) {
|
2017-10-01 15:09:38 +08:00
|
|
|
stack.push(temptop); // If stack is empty push the element
|
2019-05-09 19:32:54 +08:00
|
|
|
} else {
|
2017-10-01 15:09:38 +08:00
|
|
|
int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/
|
|
|
|
stack.pop();
|
|
|
|
|
2017-10-01 15:15:13 +08:00
|
|
|
insertAtEnd(temptop); //Recursive call
|
2017-10-01 15:09:38 +08:00
|
|
|
|
|
|
|
stack.push(temp);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|