- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteMiddleElementFromStack.java
More file actions
Latest commit
46 lines (44 loc) · 1.48 KB
/
Copy pathDeleteMiddleElementFromStack.java
File metadata and controls
46 lines (44 loc) · 1.48 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
46
packageRecursionAndBacktracking;
/*
* We have given a stack containing numbers we have to delete the middle element present in the stack.
* Middle element is present at position : (stack.size() / 2 + 1)
*/
importjava.util.Scanner;
importjava.util.Stack;
publicclassDeleteMiddleElementFromStack {
privatestaticvoiddeleteMiddle(Stack<Integer> stack, intk){
// Base condition
if(stack.size() == 0)
return;
solve(stack, k);
}
publicstaticvoidsolve(Stack<Integer> stack, intk){
// Base condition : if k==1 it means that the top element is the deleting element which we have to delete
if(k == 1){
stack.pop();
return;
}
// else
intval = stack.pop();
solve(stack, k-1);
stack.push(val);
}
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();
}
intk = stack.size()/2 + 1;
deleteMiddle(stack, k);
System.out.println(stack);
}
}
}