最近学习了环形队列,但很多代码都存在一些问题,就自己写了一份。
package queuq;
public class ArrayQueue {
private final int[] array;
private int rear;
private int front;
private int currentSize;
private final int maxSize;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
array = new int[this.maxSize + 1];
System.out.println("array.length=" + array.length);
rear = 0;
front = 0;
currentSize = 0;
}
public boolean isFull(){
return currentSize == maxSize;
}
public boolean isEmpty(){
return currentSize == 0;
}
public void enqueue(int val){
if (isFull()){
System.out.println("队列已满");
return;
}
array[rear] = val;
rear = (rear + 1) % maxSize;
currentSize++;
}
public int getRear(){
return rear;
}
public int getFront() {
return front;
}
public int dequeue(){
if (isEmpty()){
throw new RuntimeException("空");
}
currentSize--;
int res = array[front];
front = (front + 1) % maxSize;
return res;
}
public int removeLast(){
if (isEmpty()){
throw new RuntimeException("空");
}
currentSize--;
rear = this.rear == 0 ? maxSize - 1 : (rear - 1) % maxSize;
return array[rear];
}
public void findQueue(){
if (isEmpty()){
throw new RuntimeException("空");
}
for (int i = front; i < currentSize; i++){
System.out.printf("array[%d]=%d\n", i, array[i]);
}
}
public int peek(){
if (isEmpty()){
throw new RuntimeException("空");
}
return array[front];
}
public int Rear(){
if (isEmpty()){
throw new RuntimeException("空");
}
return this.rear == 0 ? array[maxSize - 1] : array[rear - 1];
}
public int size(){
return currentSize;
}
}
自己写的代码参考了数据结构java语言描述,增加了一个currentSize这个属性来记录队列的长度。
网上很多代码都是直接用rear和front来判断队列的长度,这样很难理解,而且容易出bug,还是维护一个currentSize比较方便。。