从 Java 中的堆栈中移除元素
可以使用 java.util.Stack.pop() 方法从堆栈中移除元素。此方法不需要任何参数,它将移除堆栈顶部的元素。它将返回已移除的元素。
以下给出了演示此功能的程序 −
示例
import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack); System.out.println("The element that was popped is: " + stack.pop()); System.out.println("The stack elements are: " + stack); } }
输出
The stack elements are: [Apple, Mango, Guava, Pear, Orange] The element that was popped is: Orange The stack elements are: [Apple, Mango, Guava, Pear]
现在让我们了解上述程序。
创建堆栈。然后使用 Stack.push() 方法将元素添加到堆栈。显示堆栈。以下代码片段演示了此操作 −
Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack);
Stack.pop() 方法用于移除堆栈的顶部元素并显示它。然后再次显示堆栈。以下代码片段演示了此操作 −
System.out.println("The element that was popped is: " + stack.pop()); System.out.println("The stack elements are: " + stack);
广告