Write method removeThree(Stack s) that receives a stack, and removes the three elements at the bottom of the stack. You should ensure that stack has at least three elements, otherwise display an error message. please do tin java
import java.util.Stack;
public class StackPractice{
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
System.out.print("Stack : ");
System.out.println(stack);
StackPractice stkp = new StackPractice();
stkp.removeThree(stack);
System.out.print("Popping 3 elements : ");
System.out.println(stack);
}
public void removeThree(Stack<Integer> stack) {
Stack<Integer> temp = new Stack<Integer>();
// checking size less than 3 or not
if(stack.size() < 3) {
System.out.println("Cannot remove");
return;
}
// pushing stack into temp
while(!stack.isEmpty()) {
temp.push(stack.pop());
}
// popping 3 elements
temp.pop();
temp.pop();
temp.pop();
// popping temp and pushing it to stack
while(!temp.isEmpty()) {
stack.push(temp.pop());
}
}
}
Code
Output
Get Answers For Free
Most questions answered within 1 hours.