用数组实现动态变化的堆栈
package com.algorithms.base;public class Stack<Item> { private int n; // 元素个数 private Item[] a; public Stack() { n = 0; a = (Item[]) new Object[1]; } private void reSize(int length) { Item[] temp = (Item[]) new Object[length]; for (int i = 0; i < n; i++) { temp[i] = a[i]; } a = temp; } public boolean isEmpty() { return n == 0; } public boolean isFull() { return n == a.length; } public int size() { return a.length; } public void push(Item t) { if (n == a.length) { reSize(2 * a.length); } a[n] = t; n++; } public Item pop() { n--; Item temp = a[n]; a[n] = null; if (n == a.length / 4 && n > 0) reSize(a.length / 2); return temp; }}
链表实现
package com.algorithms.base;public class LinkStack<Item> { private Node first; private int n; private class Node { Node next; Item item; } public boolean isEmpty() { return n == 0; } public Item pop() { Item temp = first.item; first = first.next; n--; return temp; } public void push(Item item) { Node oldfirst = first; first = new Node(); first.next = oldfirst; first.item = item; n++; }}