一、概念
队列是一个有序列表,可以用数组或链表来实现,遵循先进先出原则
二、数组模拟队列
1、需要维护的属性
maxSize:队列最多存放多少数据
front:头指针,指向队列头部的前一个位置,初始化为-1
rear:尾指针,指向队列尾部,初始化为-1
2、队列包含的方法
1)isEmpty
判断 rear == front
2)isFull
判断 rear == maxSize - 1
3)addQueue
a)判断队列是否已满
b)arr[++rear] = value
4)getQueue
a)判断队列是否为空
b)return arr[++front]
代码实现:
class ArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
//根据指定大小,初始化队列
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
front = -1;
rear = -1;
arr = new int[maxSize];
}
//判断队列是否为空
public boolean isEmpty() {
return rear == front;
}
//判断队列是否已满
public boolean isFull() {
return rear == maxSize - 1;
}
//向队列添加数据
public void addQueue(int value) {
//判断队列是否已满
if (isFull()) {
System.out.println("队列已满,添加失败");
return;
}
//rear指针后移一位,并赋值
arr[++rear] = value;
}
//从队列取数据
public int getQueue() {
//判断队列是否为空
if (isEmpty()) {
throw new RuntimeException("当前队列为空");
}
//front后移一位
return arr[++front];
}
//查看队头数据,注意不是取数据
public int peek() {
if (isEmpty()) {
throw new RuntimeException("当前队列为空");
}
return arr[front + 1];
}
}
3、存在问题:数组使用一次就不能再使用了,因此需要优化为环形队列
三、数组模拟环形队列
1、思路如下:
1)front:指向队列的第一个元素,初始化为0
2)rear:指向队列最后一个元素的后一个位置,初始化为0,预留了一个空间作为约定, 即假如MaxSize为4,则最大有效数据为3
3)队列满时的条件,(rear+1)%maxSize == front
4)队列空时的条件,rear == front
5)队列中有效元素的个数为:(rear+maxSize-front) % maxSize
代码实现:
class ArrayCircleQueue {
private int front;
private int rear;
private int maxSize;
private int[] arr;
public ArrayCircleQueue(int maxSize) {
this.maxSize = maxSize;
front = 0;
rear = 0;
arr = new int[maxSize];
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
public boolean isEmpty() {
return rear == front;
}
public void addQueue(int value) {
if (isFull()) {
System.out.println("队列已满");
return;
}
arr[rear] = value;
rear = (rear + 1) % maxSize;
}
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
public int peek(){
return arr[front % maxSize];
}
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = front; i < front + size(); i++) {
System.out.print(arr[i % maxSize] + "\t");
}
System.out.println();
}
public int size(){
return (rear + maxSize -front) % maxSize;
}
}