直接上代码:一些实现代码的感悟,虽不一定正确,但也代表自己的所思所想。
/**
* 〈一句话功能简述〉<br>
* 〈用固定数组实现栈〉
*
* @author Administrator
* @create 2019/5/30
* @since 1.0.0
*/
public class ArrayStack {
public static class AarryStack {
//以数组的方式理解栈,栈还是相当简单的,先进后出的
private Integer[] arr;
private Integer index;
public void StackArr(int initSize) {
if (initSize < 0) {
throw new IllegalArgumentException("the int size less than 0");//IllegalArgumentExcepion指示传入了一个非法参数
}
arr = new Integer[initSize];
index = 0;
}
public Integer peek() {//peek是返回顶部的数
if (index == 0) return null;
return arr[index - 1];
}
public void push(int num) {
if (index == arr.length) {
throw new ArrayIndexOutOfBoundsException("the array is full");
}
arr[index++] = num;
}
public Integer pop() {
if (index == 0) {
throw new ArrayIndexOutOfBoundsException("the array is empty");
}
return arr[-- index];//这里要注意,一定是弹出的index-1位置上的数,因为index始终指向下一个位置
}
}
//用固定数组理解队列,这是个重点,队列是先进先出的
//写程序过程中,还原物理操作的过程能力还是很重要的,要符合计算机特点:只要告诉计算机想要的结果,重复的过程让计算机自己去实现
//对于一段数据,一定要看作是一个整体,这样才能更快出结果,更快的将操作转换成代码.
public static class QueueArray {
private Integer[] arr;
private Integer size;
private Integer start;
private Integer end;
public void QueueArray(Integer initSize) {
if (initSize < 0) {
throw new IllegalArgumentException("the array is empty");
}
arr = new Integer[initSize];
size = 0;//进入的数据个数
start = 0;//出队
end = 0;//入队
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[start];
}
public void push(Integer num) {
if (size == arr.length) {
throw new IllegalArgumentException("the array is full");
}
size++;
arr[end] = num;
end = size == arr.length - 1 ? 0 : end + 1;//看一下数组是否已经满了,满了的话跳到最初位置
}
public Integer pop() {
if (size == 0) {
throw new IllegalArgumentException("the array is empty");
}
size--;
int temp = start;//缓存一下
start = size == arr.length ? 0 : start + 1;
return arr[temp];
}
}
}