检查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());热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短