如何在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
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练