ArrayQueue存在一个问题,假设当尾部插入元素满了,头部又删掉了一些元素,这种情况下,就误认为空间满了,造成了假溢出,实际上头部删除了元素留出了空间。这时候环形队列就解决了这样的一个问题,环形队列的front指针始终指向当前队列的最后位置;end指针始终指向第一个元素的前一个位置为-1,存储元素的时候头部和尾部都可以相互移动,而不必造成假溢出现象,节省了内存空间。如下:
1、构造方法
class CircleQueue {
//队头
private int front;
//队尾
private int end;
//队列有效长度
private int elements;
//队列
private long[] queue;
public CircleQueue() {
queue = new long[5];
front = -1;
end = -1;
}
public CircleQueue(int length) {
queue = new long[length];
front = -1;
end = -1;
}
}
2、添加队列
/**
* 插入元素
*/
public void add(int value) {
if (isFull()) {
System.out.println("队列已满,请删除");
throw new IndexOutOfBoundsException();
}
if (isEmpty()) {
front = 0;
}
if ((end == queue.length - 1)) {
end = -1;
}
queue[++end] = value;
elements++;
}
3、删除队列
/**
* 删除元素
*/
public void delete() {
if ((front == queue.length)) {
front = -1;
}
queue[front] = -1;
front++;
elements--;
}
4、查看队列元素
/**
* 查看队列
*/
public void display() {
if (isEmpty()) {
System.out.println("元素为空,请先插入元素");
}
for (int i = 0; i < queue.length; i++) {
if (queue[i] == -1) {
//X为占位符,表示该节点元素没有元素
System.out.print("X" + " ");
} else {
System.out.print(queue[i] + " ");
}
}
System.out.println();
}
5、查看队头
/**
* 查看队头
*/
public long getFront() {
if (isEmpty()) {
System.out.println("队尾为空");
return 0;
}
return queue[front];
}
6、查看队尾
/**
* 查看队尾
*/
public long getEnd() {
if (isEmpty()) {
return -1;
}
return queue[end];
}
7、查看队列元素个数
/**
* 查看队列里面几个元素
*/
public int size() {
return elements;
}
8、队列是否为空
/**
* 队列是否为空
*/
public boolean isEmpty() {
return elements == 0;
}
9、队列是否满了
/**
* 队列是否满了
*/
public boolean isFull() {
return elements == queue.length;
}
下一篇将介绍优先队列。