后进者先出,先进者后出,这就是典型的“栈”结构。
如有不对的地方请指出,共同提高,谢谢!
数据结构如图(虽然的确是丑了点):
代码如下:
1 /** 2 * @Author:shenqi 3 * @Description: 用数组实现的栈,不支持动态扩容,如要支持就自行copy数组,并扩大数组的容量 4 * @Date:2019/1/14 12:24 5 */ 6 public class ArrayStack { 7 8 private Object[] arrays; 9 private int size; // 数组的容量 10 private int count;// 放入的个数 11 12 /** 13 * 初始化 14 * 15 * @param size 16 */ 17 public ArrayStack(int size) { 18 this.size = size; 19 this.arrays = new Object[size]; 20 } 21 22 /** 23 * 放入元素 24 * 25 * @param o 26 */ 27 public void push(Object o) { 28 if (size == count) { 29 throw new ArrayIndexOutOfBoundsException(); 30 } 31 arrays[count] = o; 32 count++; 33 } 34 35 /** 36 * 获取元素 37 * 38 * @return 39 */ 40 public Object pop() { 41 if (count == 0) 42 throw new ArrayIndexOutOfBoundsException(); 43 Object o = arrays[count - 1]; 44 count--; 45 return o; 46 } 47 }