检查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("\nThe 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("\nThe 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.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("\nThe 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("\nThe stack elements are: " + stack);
System.out.println("The stack is empty? " + stack.empty());热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿