数组模拟队列的简单实现方式代码如下:
public class ArrayQueue {
private int maxSize;
private int front;
private int tail;
private int[] array;
public ArrayQueue(int queueSize) {
maxSize = queueSize;//最大元素个数
array = new int[queueSize];
front = -1;//头结点
tail = -1;//尾结点
}
private boolean isEmpty() {
return front == tail;
}
private boolean isFull() {
return maxSize == front + 1;
}
//添加元素
public void addQueue(int i) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
tail++;
array[tail] = i;
}
//获取元素
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
front++;
return array[front];
}
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = 0; i <maxSize ; i++) {
System.out.printf("队列第 %d 个元素为: %d ", i, array[i]);
}
}
}
存在问题,加入队列在数组下标为1的地方添加了元素,当这个元素出队列后,这个数组的位置不能重复使用,会有空间浪费的问题
解决方式,环形队列实现
public class CircleQueue {
private int maxSize;//最大元素个数
private int front;//首节点位置
private int tail;//尾结点位置的前一个位置
private int[] array;
public CircleQueue(int queueSize) {
maxSize = queueSize;
array = new int[queueSize];
}
private boolean isEmpty() {
return front == tail;
}
/**
* 判断队列是否已满
* 例如:最大元素为4,因为tail指向尾结点前一个位置,栈中最多能存3个元素,
* 如果tail=3,front=0,此时栈中元素已满。满足(tail + 1) % maxSize == front
*/
private boolean isFull() {
return (tail + 1) % maxSize == front;
}
//添加元素
public void addQueue(int i) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
array[tail] = i;
//加入tail为3,0的位置是空的,则(3+1)%4 = 0,刚好tail的值置为0,
tail = (tail + 1) % maxSize;
}
//获取元素
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
//这里front是指向队列的第一个元素
//先将front对应的值保存到一个临时变量
//将front后移,考虑取模形成一个环
//返回临时变量
int value = array[front];
front = (front + 1) % maxSize;
return value;
}
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = front; i < front + size(); i++) {
System.out.printf("array[%d]=%d\n", i % maxSize, array[i % maxSize]);
}
}
//返回队列的有效元素个数
public int size() {
return (tail + maxSize - front) % maxSize;
}
}