- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
Latest commit
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
packageRecursionAndBacktracking;
/*
* Reverse stack using recursion without using extra space.
*/
importjava.util.Scanner;
importjava.util.Stack;
publicclassReverseStack {
privatestaticvoidreverseStack(Stack<Integer> stack){
// Base Condition
if(stack.size() == 1)
return;
intval = stack.pop();
reverseStack(stack);
pushValAtEnd(stack, val);
}
publicstaticvoidpushValAtEnd(Stack<Integer> stack, intval){
// Base condition
if(stack.size() == 0){
stack.push(val);
return;
}
inttemp = stack.pop();
pushValAtEnd(stack, val);
stack.push(temp);
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
System.out.println("Enter the number of test cases:");
intt = sc.nextInt();
while (t-- > 0) {
System.out.println("Enter elements: if want to stop enter -1");
Stack<Integer> stack = newStack<>();
intele = 0;
ele = sc.nextInt();
while (ele != -1){
stack.push(ele);
ele = sc.nextInt();
}
reverseStack(stack);
System.out.println(stack);
}
}
}