package Stack; public class Stack<E> {// 不知道栈中要存入什么类型,用泛型 /** * @param PLA * JAVA实现简单堆栈 */ private Object[] stack;// java不支持泛型数组(可以用其它容器来使用) private int index;// 充当指针 private static final int SIZE = 5;// 默认栈的初始大小 // 默认构造器 public Stack() { stack = new Object[SIZE]; index = -1; } // 带参数的构造器 public Stack(int size) { if (size < 0) { System.out.println("所输入的栈的大小不合法"); throw new IllegalArgumentException(); } stack = new Object[size]; index = -1; } // 入栈操作 public synchronized void push(E data) { if (isFull()) {// 若栈满了,创建一个新栈,容量为当前栈的两倍 Object[] temp = stack; stack = new Object[temp.length * 2]; System.arraycopy(temp, 0, stack, 0, temp.length); System.out.println("当前栈已满,已创建新栈,容量扩充一倍"); } stack[++index] = data; } // 出栈操作 public synchronized E poll() { if (!isEmpty()) { E temp = getTop(); stack[index--] = null; return temp; } return null; } // 获取栈顶对象 public E getTop() { return (E) stack[index]; } public boolean isFull() { return index >= stack.length - 1; } public boolean isEmpty() { return index == -1; } public static void main(String[] args) { // TODO Auto-generated method stub /* * Stack<Integer> s = new Stack<Integer>(3); s.push(2); s.push(4); * s.push(6); System.out.println(s.poll()); * System.out.println(s.poll()); System.out.println(s.poll()); * System.out.println(s.poll()); */ Stack<String> s = new Stack<String>(3); s.push("哈哈1"); s.push("哈哈2"); s.push("哈哈3"); s.push("哈哈4"); System.out.println(s.poll()); System.out.println(s.poll()); System.out.println(s.poll()); System.out.println(s.poll()); System.out.println(s.poll()); } }
运行结果:
当前栈已满,已创建新栈,容量扩充一倍 哈哈4 哈哈3 哈哈2 哈哈1 null