To delete the intermediate element of the stack, you first need to remove the element above the intermediate element. After removing the intermediate elements, the elements above them need to be restored to maintain the original order. This operation can be implemented using a recursive method, as described below.
Due to the characteristics of the stack, we can only perform stack pressing and stacking operations on the top of the stack, so we cannot directly delete the intermediate elements of the stack.
Step 1: Determine the position of the intermediate element First, you need to determine the intermediate element of the stack, the method is as follows:
Step 2: Recursively remove the element at the top of the stack until the intermediate element is reached.
Step 3: Once the intermediate element is reached, just pop it out of the stack and reassemble the stack to its original order.
The following example deletes the intermediate element of the stack:
import java.util.Stack; public class Example { public static void deleteMidElement(Stack<Integer> stack, int currentIndex) { if (currentIndex == 0) { stack.pop(); return; } int temp = stack.pop(); deleteMidElement(stack, currentIndex - 1); stack.push(temp); } public static void main(String args[]) { Stack<Integer> stack = new Stack<>(); stack.push(9); stack.push(10); stack.push(0); stack.push(5); stack.push(7); int N = stack.size() / 2; System.out.println("删除中间元素之前的堆栈: " + stack); deleteMidElement(stack, N); System.out.println("删除中间元素之后的堆栈: " + stack); } }
The output of the above program is as follows:
<code>删除中间元素之前的堆栈: [9, 10, 0, 5, 7] 删除中间元素之后的堆栈: [9, 10, 5, 7]</code>
In the main
method, we call the deleteMidElement()
method, the parameters are the index of the stack and the intermediate elements.
In the deleteMidElement()
method, we check whether currentIndex
is equal to 0. If true, the top of the stack is an intermediate element; otherwise, store the top of the stack in a variable, call deleteMidElement()
recursively, decrement currentIndex
by one each time, and then push the stored element back on the stack.
The above is the detailed content of Delete middle element of a stack in Java. For more information, please follow other related articles on the PHP Chinese website!