数组实现栈
package com.yudaodata.protocol809.task;
import java.util.Arrays;
import java.util.EmptyStackException;
public class ArrayStack<T> {
private Object[] elements = new Object[16]; //数组大小默认16
private int count; //1.-1后指向栈内末尾的元素 2.统计栈内元素的数量
public void push(T e) {
//数组扩容
if (count == elements.length) {
elements = Arrays.copyOf(elements, 2 * count + 1);
}
elements[count++] = e;
}
public T pop() {
if (count == 0) {
throw new EmptyStackException();
}
T o = (T) elements[--count];
elements[count] = null; //防止内存泄漏
return o;
}
public static void main(String[] args) {
ArrayStack<Integer> arrayStack = new ArrayStack<>();
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
System.out.println(arrayStack.pop()); //2
System.out.println(arrayStack.pop()); //1
System.out.println(arrayStack.pop()); //1
}
}
种桃道士归何处,前度刘郎今又来。