用数组结构实现大小固定的栈和队列
public class Array_To_Stack_Queue {
public static class ArrayStack {
private Integer[] arr;
private Integer index; //构建一个指针index,数组中没有数时指向0,在数组的0位置添加一个数后index指向1
public ArrayStack(int initSize) {
if (initSize < 0) {
throw new IllegalArgumentException("The init size is less than 0");
}
arr = new Integer[initSize];
index = 0;
}
public Integer peek() { //返回栈顶元素但不移除它
if (index == 0) {
return null;
}
return arr[index - 1]; //index往下一位指向的才是栈顶
}
public void push(int obj) { //添加操作
if (index == arr.length) {
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
arr[index++] = obj;
}
public Integer pop() { //弹出操作
if (index == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
//在数组0位置添加一个数后index指向1,执行弹出操作时需要index往下移一位指向0位置的数,表示弹出了,后续添加操作加入的数会直接覆盖此时0位置的数。
return arr[--index];
}
}
public static class ArrayQueue {
private Integer[] arr;
private Integer size;
private Integer start;
private Integer end;
public ArrayQueue(int initSize) {
if (initSize < 0) {
throw new IllegalArgumentException("The init size is less than 0");
}
arr = new Integer[initSize];
size = 0;
start = 0;
end = 0;
}
public Integer peek() { //返回队顶元素但不移除它
if (size == 0) {
return null;
}
return arr[start];
}
public void push(int obj) { //添加操作,size加1,end加1
if (size == arr.length) {
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
size++;
arr[end] = obj;
end = end == arr.length - 1 ? 0 : end + 1; //如果end已经指向末尾,由于进行添加操作后end需要加1,所以把end移到数组开头
}
public Integer poll() { //弹出操作,size减1,start加1
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
size--;
int tmp = start;
start = start == arr.length - 1 ? 0 : start + 1; //如果start已经指向数组末尾,由于进行弹出操作后start需要加1,所以把start移到数组开头
return arr[tmp];
}
}
}