Although I would recommend you use a different data structure, such as linked listif you want to remove from the middle, because there is one for this linked lists. You should NOT use ALL stacks if you want to remove an item from the middle. But since the question asks the question, then you can introduce a method deleteFrom()as shown below.
: , , , .
[a] TOP
[a, b] TOP
[a, b, c] TOP
After calling deleteFrom(stack, "b")
[a, c] TOP
deleteFrom():
public static Stack<String> deleteFrom(Stack<String> stack, String obj) {
if (stack.search(obj) == -1) {
System.out.println("Element doesn't exists in stack.");
return stack;
}
Stack<String> stack2 = new Stack<String>();
while (stack.search(obj) != -1)
stack2.push(stack.pop());
stack2.pop();
while (stack2.size() != 0)
stack.push(stack2.pop());
return stack;
}
:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("a");
printStack(stack);
stack.push("b");
printStack(stack);
stack.push("c");
printStack(stack);
stack = deleteFrom(stack, "b");
System.out.println("After calling deleteFrom(stack, \"b\")");
printStack(stack);
}
private static void printStack(Stack<String> s) {
if (s.isEmpty()) {
System.out.println("empty stack");
} else {
System.out.printf("%s TOP\n", s);
}
}
public static Stack<String> deleteFrom(Stack<String> stack, String obj) {
if (stack.search(obj) == -1) {
System.out.println("Element doesn't exists in stack.");
return stack;
}
Stack<String> stack2 = new Stack<String>();
while (stack.search(obj) != -1)
stack2.push(stack.pop());
stack2.pop();
while (stack2.size() != 0)
stack.push(stack2.pop());
return stack;
}
}