数组实现队列
public class ArrayImplementsQueue {
private int[] arr;
private int pushIndex;
private int pollIndex;
private int size;
private int limit;
public ArrayImplementsQueue(int num) {
this.arr = new int[num];
this.pushIndex = 0;
this.pollIndex = 0;
this.size = 0;
this.limit = num;
}
public void push(int value) {
if (size == limit) {
throw new RuntimeException("数组已满,无法添加");
}
size++;
arr[pushIndex]=value;
pushIndex = newIndex(pushIndex);
}
public int poll() {
if (size == 0) {
throw new RuntimeException("数组已空,无法弹出");
}
size--;
int a=arr[pollIndex];
pollIndex = newIndex(pollIndex);
return a;
}
public int newIndex(int i) {
return i < limit - 1 ? i + 1 : 0;
}
}