在 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());

更新於:2020 年 6 月 25 日

3K+ 瀏覽量

開啟您的職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.