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