從 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);
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP