在 Java 中檢查棧是否為空
java.util.Stack.empty() 方法用於檢查棧是否為空。此方法不需要引數。如果棧為空,它返回 true;如果棧不為空,它返回 false。
展示這一點的程式如下 −
示例
import java.util.Stack;
public class Demo {
public static void main (String args[]) {
Stack stack = new Stack();
stack.push("Amy");
stack.push("John");
stack.push("Mary");
System.out.println("The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
System.out.println("
The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("
The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
}
}輸出
The stack elements are: [Amy, John, Mary] The stack is empty? false The element that was popped is: Mary The element that was popped is: John The element that was popped is: Amy The stack elements are: [] The stack is empty? true
現在讓我們瞭解上面的程式。
建立了 Stack。然後使用 Stack.push() 方法將元素新增到棧中。顯示棧,然後使用 Stack.empty() 方法檢查棧是否為空。演示這一點的程式碼片段如下:
Stack stack = new Stack();
stack.push("Amy");
stack.push("John");
stack.push("Mary");
System.out.println("The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());Stack.pop() 方法用於彈出三個棧元素。顯示棧,然後使用 Stack.empty() 方法檢查棧是否為空。演示這一點的程式碼片段如下:
System.out.println("
The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("The element that was popped is: " + stack.pop());
System.out.println("
The stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP