堆栈(Stack),是计算机科学中一种特殊的串列形式的抽象数据类型,只允许在栈顶进行 push 和 pop 操作,按照后进先出的规则。
继承 Vector 类
public class Stack<E> extends Vector<E> { /** * Creates an empty Stack. */ public Stack() { } /** * push 输入对象 */ public E push(E item) { addElement(item); return item; } /** * pop 输出栈顶对象 */ public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj; } /** * 查看 栈顶 对象 */ public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } /** * 判断 堆栈是否为空 */ public boolean empty() { return size() == 0; } /** * 返回对象在堆栈中距离栈顶的距离 */ public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 1224463164541339165L; }
测试 Stack 方法
public class StackTest { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(0); stack.push(1); stack.push(2); stack.push(3); stack.push(4); System.out.println("1----->栈顶------->" + stack.peek()); stack.pop(); System.out.println("2----->栈顶 pop 后------->" + stack.peek()); stack.push(5); System.out.println("3----->栈顶 push 5 后------->" + stack.peek()); System.out.println("4----->判断是否为空------->" + stack.empty()); System.out.println("5----->查询 3 在堆栈中与栈顶的距离------->" + stack.search(3)); } }