如何在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 送教授贺卡祝福语简短
13 会计祝福语毕业英语简短
14 猪年祝福语大全简短的
15 客户祝福语事业文案简短
16 女儿生日祝福语英语简短
17 对新人祝福语大全简短
18 开盘大吉的简短祝福语