用数组实现动态变化的堆栈

  1. package com.algorithms.base;
  2. public class Stack<Item> {
  3. private int n; // 元素个数
  4. private Item[] a;
  5. public Stack() {
  6. n = 0;
  7. a = (Item[]) new Object[1];
  8. }
  9. private void reSize(int length) {
  10. Item[] temp = (Item[]) new Object[length];
  11. for (int i = 0; i < n; i++) {
  12. temp[i] = a[i];
  13. }
  14. a = temp;
  15. }
  16. public boolean isEmpty() {
  17. return n == 0;
  18. }
  19. public boolean isFull() {
  20. return n == a.length;
  21. }
  22. public int size() {
  23. return a.length;
  24. }
  25. public void push(Item t) {
  26. if (n == a.length) {
  27. reSize(2 * a.length);
  28. }
  29. a[n] = t;
  30. n++;
  31. }
  32. public Item pop() {
  33. n--;
  34. Item temp = a[n];
  35. a[n] = null;
  36. if (n == a.length / 4 && n > 0)
  37. reSize(a.length / 2);
  38. return temp;
  39. }
  40. }

链表实现

  1. package com.algorithms.base;
  2. public class LinkStack<Item> {
  3. private Node first;
  4. private int n;
  5. private class Node {
  6. Node next;
  7. Item item;
  8. }
  9. public boolean isEmpty() {
  10. return n == 0;
  11. }
  12. public Item pop() {
  13. Item temp = first.item;
  14. first = first.next;
  15. n--;
  16. return temp;
  17. }
  18. public void push(Item item) {
  19. Node oldfirst = first;
  20. first = new Node();
  21. first.next = oldfirst;
  22. first.item = item;
  23. n++;
  24. }
  25. }