1. Introduction
In many applications, there might arise a need to modify the content of a stack. One such modification can be to delete the middle element of the stack. In this tutorial, we’ll explore how to delete the middle element from a stack in Java.
2. Program Steps
1. Define a Stack class with standard operations: push(), pop(), peek(), and isEmpty().
2. Create a recursive function, deleteMiddle, which will delete the middle element of the stack.
3. Use this function to delete the middle element and then display the updated stack.
3. Code Program
import java.util.Stack;
public class DeleteMiddleElement {
public static void deleteMiddle(Stack<Integer> stack, int n, int curr) {
// Base condition, if stack is empty or all items are traversed
if (stack.isEmpty() || curr == n) {
return;
}
// Store the current item
int temp = stack.pop();
// Recur for remaining items
deleteMiddle(stack, n, curr+1);
// Push the current item back to the stack except for the middle element
if (curr != n/2) {
stack.push(temp);
}
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < 5; i++) {
stack.push(i);
}
System.out.println("Original Stack: " + stack);
deleteMiddle(stack, stack.size(), 0);
System.out.println("Stack after deleting middle: " + stack);
}
}
Output:
Original Stack: [0, 1, 2, 3, 4] Stack after deleting middle: [0, 1, 3, 4]
4. Step By Step Explanation
1. We begin by initializing a standard Java Stack and populating it with elements.
2. The deleteMiddle function takes the stack, its size n, and a counter curr to keep track of the current position while traversing the stack.
3. If the stack is empty or if we've traversed all items, we exit from the function.
4. We then pop the current item from the stack and recursively call deleteMiddle for the remaining items.
5. While coming back from the recursion, we push all elements back onto the stack except the middle one.
6. The middle element can be determined by the condition curr != n/2.
Using this recursive approach, we can delete the middle element while preserving the order of other elements in the stack.