-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
45 lines (43 loc) · 1.31 KB
/
Copy pathReverseStack.java
File metadata and controls
45 lines (43 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package RecursionAndBacktracking;
/*
* Reverse stack using recursion without using extra space.
*/
import java.util.Scanner;
import java.util.Stack;
public class ReverseStack {
private static void reverseStack(Stack<Integer> stack){
// Base Condition
if(stack.size() == 1)
return;
int val = stack.pop();
reverseStack(stack);
pushValAtEnd(stack, val);
}
public static void pushValAtEnd(Stack<Integer> stack, int val){
// Base condition
if(stack.size() == 0){
stack.push(val);
return;
}
int temp = stack.pop();
pushValAtEnd(stack, val);
stack.push(temp);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of test cases:");
int t = sc.nextInt();
while (t-- > 0) {
System.out.println("Enter elements: if want to stop enter -1");
Stack<Integer> stack = new Stack<>();
int ele = 0;
ele = sc.nextInt();
while (ele != -1){
stack.push(ele);
ele = sc.nextInt();
}
reverseStack(stack);
System.out.println(stack);
}
}
}