从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);