Java 泛型数组实现栈:pop、push、peek 操作
下面是用数组实现的一个泛型栈类,包含pop、push和peek方法:
public class ArrayStack<E> {
private Object[] array;
private int top;
private int capacity;
public ArrayStack(int capacity) {
this.capacity = capacity;
array = new Object[capacity];
top = -1;
}
public void push(E element) {
if (top == capacity - 1) {
throw new StackOverflowError("Stack is full");
}
array[++top] = element;
}
public E pop() {
if (top == -1) {
throw new EmptyStackException();
}
E element = (E) array[top];
array[top--] = null;
return element;
}
public E peek() {
if (top == -1) {
throw new EmptyStackException();
}
return (E) array[top];
}
}
使用示例:
public class Main {
public static void main(String[] args) {
ArrayStack<Integer> stack = new ArrayStack<>(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.peek()); // 输出 3
System.out.println(stack.pop()); // 输出 3
System.out.println(stack.pop()); // 输出 2
stack.push(4);
stack.push(5);
System.out.println(stack.pop()); // 输出 5
System.out.println(stack.pop()); // 输出 4
System.out.println(stack.pop()); // 输出 1
// System.out.println(stack.pop()); // 抛出 EmptyStackException 异常
}
}
原文地址: https://www.cveoy.top/t/topic/ppbe 著作权归作者所有。请勿转载和采集!