数组实现队列
设置3个变量,size记录队列长度,first记录头指针,last记录尾部的下一个节点。
代码如下:
public static class ArrayQueue {
private Integer[] arr;
private Integer size;
private Integer first;
private Integer last;
private ArrayQueue(int initSize) {
if (initSize == 0) {
throw new IllegalArgumentException("this init size is less than 0");
}
arr = new Integer[initSize];
size = 0;
first = 0;
last = 0;
}
public int peek() {
if (size==0) {
return null;
}
return arr[first];
}
public void push(int a) {
if (size == arr.length) {
throw new ArrayIndexOutOfBoundsException("index out of bounds");
}
size++;
arr[last] = a;
last = last==arr.length-1 ? 0:last+1;
}
public int poll() {
if (size==0) {
throw new ArrayIndexOutOfBoundsException("empty");
}
size--;
int temp = first;
first = first==arr.length-1 ? 0:first+1;
return arr[temp];
}
}
数组实现栈
public static class ArrayStack {
private Integer size;
private Integer[] arr;
public static int peek() {
if (size == 0){
throw new ArrayIndexOutOfBoundsException("EMPTY");
}
return arr[size-1];
}
public static void push(int a) {
if (size == arr.length) {
throw new ArrayIndexOutOfBoundsException("full");
}
arr[size++] = a;
}
public static int pop() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("empty");
}
return arr[--size];
}
}