数组实现队列
package com.gaiwey.algorithm;
public class MyQueue {
private int[] arr;
private int size;
private int pushindex;
private int pollindex;
private int limit;
public MyQueue(int limit) {
arr = new int[limit];
size = 0;
pushindex = 0;
pollindex = 0;
this.limit = limit;
}
public void push(int i) {
if (isFull()) {
throw new RuntimeException("队列已满,无法添加元素啦……");
}
arr[pushindex] = i;
size++;
pushindex = nextIndex(pushindex);
}
public int poll() {
if (isEmpty()) {
throw new RuntimeException("队列已空,无法取出元素啦……");
}
int i = arr[pollindex];
size--;
pollindex = nextIndex(pollindex);
return i;
}
public boolean isEmpty(){
return size==0?true:false;
}
public boolean isFull(){
return size==limit?true:false;
}
private int nextIndex(int i){
return i < arr.length - 1 ? i + 1 : 0;
}
}