【原理】:用固定数组大小实现,栈结构,先进后出,
- 用构造方法初始化数组(数组大小 = initSize,index指针 = 0)
- 用方法实现,push, pop , peek 功能
- push:(先判定是否越界,index==arr.length)新来的数字永远放入index指向位置,完成后index++
- pop: (先判定是否越界失效,栈里没数时候,index == 0, 无法弹出),由于每次新增数后,index跑到下一个内存空间,如果这时候需要弹出数字,则先将index减1,所以是--index。指针
- peek: 弹出栈顶,与pop基本一样,pop弹出后数字不管了,peek弹出后 return arr[index-1]
【代码】:
// 1 -> “用数组结构实现大小固定的栈”
public class ArrayStack_01 {
private Integer[] arr;
private Integer index;
// 构造方法,初始化数组
public ArrayStack_01(int initSize) {
if(initSize < 0) {
throw new IllegalArgumentException("The init size is less than 0");
}
arr = new Integer[initSize];
index = 0;
}
// 添加push--成员方法:当index等于数组长度时候,不能再加了,(index指向的位置填入新数,index++)
public void push (int obj) {
if (index == arr.length) {
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
arr[index++] = obj;
}
// 弹出pop--成员方法, 给我,不用管它了,释放了: 让index先减1位,弹出那个数
public Integer pop() {
if (index == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
return arr[--index];
}
// peek返回栈顶留着它 -- 成员方法
public Integer peek() {
if (index == 0) {
return null;
}
return arr[index-1];
}
public static void main(String[] args) {
int len = 3;
ArrayStack_01 myArrayStack = new ArrayStack_01(len);
for(int i = 0; i<len; i++) {
myArrayStack.push(i);
}
for (int j = 0; j < len; j++) {
System.out.println("第" +j + "次弹出数字: " + myArrayStack.pop());
}
}
}
【运行结果】
第0次弹出数字: 2
第1次弹出数字: 1
第2次弹出数字: 0
【笔记】