如何在Java中使用Stack类?
Stack是java.util.Vector提供LIFO(后进先出)数据结构的类的扩展。此类提供了诸如push()和pop()的常用方法。peek方法用于获取堆栈的顶部元素,而无需删除该项目。
package org.nhooo.example.util;
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
// 我们将一些值存储在堆栈对象中。
for (int i = 0; i < 10; i++) {
stack.push(i);
System.out.print(i + " ");
}
System.out.println("");
//搜索堆栈中的项目。职位退回
//作为距堆栈顶部的距离。在这里我们搜索
// 在堆栈的第7行中的3号
// 堆栈。
int position = stack.search(3);
System.out.println("Search result position: " + position);
// 当前栈顶值
System.out.println("Stack top: " + stack.peek());
// 在这里,我们弹出所有堆栈对象项。
while (!stack.empty()) {
System.out.print(stack.pop() + " ");
}
}
}代码段的结果:
0 1 2 3 4 5 6 7 8 9 Search result position: 7 Stack top: 9 9 8 7 6 5 4 3 2 1 0
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短