【数据结构】栈-数组的实现

前端之家收集整理的这篇文章主要介绍了【数据结构】栈-数组的实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

首先是定义栈的基本结构,因为用数组实现

  1. private String[] stack;
  2. private int TOP = 0;

然后是构造方法
  1. StackOfStrings(int capacity) {
  2. stack = new String[capacity];
  3. }

然后是push,注意,TOP永远指向的是压入元素的后一位。
  1. public void push(String str) {
  2. if (TOP == stack.length) // if full,increase the stack size
  3. resize(2 * stack.length);
  4. stack[TOP++] = str;
  5. }

然后是pop
  1. public String pop() {
  2. String popItem = stack[--TOP];
  3. // if equal to 1/4,decrease the stack size
  4. if (TOP > 0 && TOP == stack.length / 4)
  5. resize(stack.length / 2);
  6. return popItem;
  7. }


然后是判空操作,想想为什么空的时候 TOP是0
  1. public boolean isEmpty() {
  2. return TOP == 0;
  3. }

最后附上resize的代码
  1. public void resize(int capacity) {
  2. String[] temp = new String[capacity];
  3. for (int i = 0; i < TOP; i++)
  4. temp[i] = stack[i];
  5. stack = temp;
  6. }

猜你在找的数据结构相关文章