队列
队列介绍
1)队列是一个有序列表,可以用数组或是链表来实现
2)遵循先入先出的原则
3)示意图
数组模拟队列
**思路分析:**当我们将数据存入队列时称为”addQueue“,addQueue的处理需要两个步骤:
1)将尾部指针往后移动:rear + 1,当rear == front【空队列】
2)若尾部指针rear小于队列最大下标,则表示可以将数据存入队列中,否则无法存入数据。rear==maxSize-1【满队列】
代码实现:
//使用数组模拟队列 编写ArrayQueue类
class ArrayQueue{
private int maxSize;//表示队列的最大容量
private int front;//表示队列的头
private int rear;//表示队列的尾部
private int[] array;//用于存放数据
//创建队列的构造器,初始化队列
public ArrayQueue(int arrMaxSize){
this.maxSize = arrMaxSize;
array = new int[maxSize];
front = -1;//指向队列的头部
rear = -1;//指向队列的尾部
}
//判断队列是否已满
public boolean isFull(){
return this.rear == maxSize - 1;
}
//判断队列是否为空
public boolean isEmpty(){
return this.rear == this.front;
}
//添加数据到队列中
public void addQueue(int data){
if (isFull()){
System.out.println("队列已满");
return;
}
this.rear++;//让尾部指针后移
array[this.rear] = data;
}
//出队列
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空,不能取数据");
}
this.front++;
return array[this.front];
}
//显示数据
public void showQueue(){
//遍历
if (isEmpty()){
System.out.println("队列为空");
return;
}
for (int i = 0;i < array.length;i++){
System.out.printf("array[%d]=%d",i,array[i]);
}
}
//显示头部数据
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("空队列");
}
return array[this.front + 1];
}
}
问题分析并优化:
1)目前数组使用一次就不能在使用了,没有达到复用的效果
2)将这个数组使用算法,改为环形队列 取模
数组模拟环形队列
思路分析:
1)front变量的含义做一个调整:front就指向队列的第一个元素,也就是说**arr[front]**就是队列的第一个元素
2)rear变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置,希望空出一个空间作为约定
3)当队列满时,条件是**(rear + 1) % maxSize = front**【满】
4)队列为空的条件rear = front
5)队列中有效数据为:(rear + maxSize - front)* maxSize
代码实现:
package com.cwnu.queue;
public class CircleArrayQueue {
/*front变量的含义做一个调整:front就指向队列的第一个元素,也就是说**arr[front]**就是队列的第一个元素
front的初始值为0
rear变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置,希望空出一个空间作为约定
rear的初始值为0*/
private int maxSize;//表示队列的最大容量
private int front;//表示队列的头
private int rear;//表示队列的尾部
private int[] array;//用于存放数据
public CircleArrayQueue(int maxSize){
this.maxSize = maxSize;
this.array = new int[this.maxSize];
}
//判断队列是否已满
public boolean isFull(){
return (this.rear + 1) % this.maxSize == this.front;
}
//判断是否为空
public boolean isEmpty(){
return this.rear == this.front;
}
//添加数据到队列中
public void addQueue(int data){
if (isFull()){
System.out.println("队列已满");
return;
}
array[this.rear] = data;
this.rear = (this.rear + 1) % this.maxSize;//指针后移
}
//出队列
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空,不能取数据");
}
//这里需要分析出front是指向队列的第一个元素
int value = this.array[this.front];//先将值取出
this.front = (this.front + 1) % maxSize;
return value;
}
//显示数据
public void showQueue(){
//遍历
if (isEmpty()){
System.out.println("队列为空");
return;
}
//思路:从front开始遍历,遍历多少个元素
for (int i = this.front;i < this.front + size();i++){
System.out.printf("array[%d]=%d",i % this.maxSize,array[i % maxSize]);
}
}
//显示队列的头数据
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("空队列");
}
return array[this.front ];
}
//获得队列的有效数据
public int size(){
return (this.rear + this.maxSize - this.front) % this.maxSize;
}
}