1.什么是队列:
队列是一个有序列表,可以用数组或是链表来实现。
遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出
2.利用数组模拟一个队列
队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图, 其中 maxSize 是该队列的最大容量,因为队列的输出、输入是分别从前后端来处理,因此需要两个变量 front及 rear分别记录队列前后端的下标,front 会随着数据输出而改变,而 rear则是随着数据输入而改变,如图所示:
3.数组模拟队列的代码实现思路
当我们将数据存入队列时称为”addQueue”,addQueue 的处理需要有两个步骤:思路分析
1)将尾指针往后移:rear+1 , 当front == rear 【空】
2)若尾指针 rear 小于队列的最大下标 maxSize-1,则将数据存入 rear所指的数组元素中,否则无法存入数据。 rear == maxSize - 1[队列满]
4.代码实现
package com.carry.数据结构和算法.队列.数组模拟队列;
public class ArrayQueue {
private int rear; //队列尾
private int font; // 队列头
private int maxSize;
private int[] arr; //存放队列的数据
public ArrayQueue(int arrayMaxSize) {
this.maxSize = arrayMaxSize;
this.arr = new int[this.maxSize];
this.font = -1;
this.rear = -1;
}
//判断队列是否为空
public boolean isEmpty() {
return rear == font;
}
//判断队列是否溢出
public boolean isFull() {
return rear == maxSize - 1;
}
//添加数据到队列里去
public void addQueue(int elem) {
if (isFull()) {
System.out.println("队列已满");
return;
}
rear++;
arr[rear] = elem;
}
//获取队列的数据
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
font++;
return arr[font];
}
//显示队列的所有数据
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空");
}
for (int i = 0; i < arr.length; i++) {
System.out.println("元素:" + arr[i]);
}
}
//显示队列头的数据
public int showHeadQueue(){
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return arr[font+1];
}
}
5.这种实现的弊端
数组使用一次就不能再用了,没有达到复用的效果。如图:
解决方案:利用一个环形队列,下节分享
可以将数组看成一个环形的(通过取模的方式实现)哎,我反正是想不到这么做,感觉自己没有搞算法的天赋,太笨了
分析:1)尾索引的下一个为头索引时表示队列满,即将队
列容量空出一个作为约定,这个在做判断队列满的
时候需要注意 (rear + 1) % maxSize == front 满]
2)rear == front [空]
代码实现:
package com.carry.数据结构和算法.队列.循环队列;
public class CircleArrayQueue {
private int rear; //队列尾,rear初始值为0,做一个约定,指向最后一个元素的后一个位置
private int font; // 队列头,font初始值为0,指向队列的第一个元素
private int maxSize;
private int[] arr; //存放队列的数据
public CircleArrayQueue(int arrayMaxSize) {
this.maxSize = arrayMaxSize;
this.arr = new int[maxSize];
}
//判断队列是否已经满了
public boolean isFull() {
return (rear + 1) % maxSize == font;
}
//判断队列是否为空
public boolean isEmpty() {
return rear == font;
}
//添加数据到队列里去
public void addQueue(int elem) {
if (isFull()) {
System.out.println("队列已满");
return;
}
//直接将数据加入
arr[rear] = elem;
//并将rear后移,这里需要考虑到取模
rear = (rear + 1) % maxSize;
}
//获取队列的数据
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
//font是指向队列的第一个元素,先把font保留到一个零时变量,吧font后移,考虑取模,把零食变量返回
int value = arr[font];
font = (font + 1) % maxSize;
return arr[font];
}
//显示队列的所有数据
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空");
}
for (int i = 0; i < font + (rear + maxSize - font) % maxSize; i++) {
System.out.println("元素:" + arr[i % maxSize]);
}
}
//显示队列头的数据
public int showHeadQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return arr[font];
}
}
这个取模的思想,需要仔细思考下,应用场景很多的