队列
先进先出。insert入队列,remove出队列。数组实现有队列空,队列满。
数组实现队列
数组实现简单队列有头和尾“指针”。插入元素,队尾rear指针上移加1。移除元素,队头指针上移加1。
环绕处理(循环队列)
为了避免队列不满却不能插入数据项的情况,可以让队头队尾指针绕回到数组开始的位置,这就是循环队列(有时也称为“缓存环”)。循环队列通过nItems数据项计数字段来记录队列内元素个数,判断队列空满状态。有数据项记录数的队列,会带来一个问题,当队头队尾取一定位置时,无法判断队列状态处于空还是满。如下面实验代码中,当front指针指向0,rear指针指向3时,队列可能为空,也可能为满。解决这个问题的办法是让数组的长度比队列数据项个数最大值大1,也就是说,数组长度比队列最大长度大1。不带nItems数据记录项的队列,需要通过front和rear的复杂计算size(),isEmpty(),isFull(),因而很少用数组长度比队列最大长度大1的方法来实现队列。
带nItems的队列
package com.dstructure.queue;
/**
* @ClassName Queue
* @Author gg_girl
* @Date 2020/9/4
* @Description 循环队列
* 有数据项计数字段的队列
* 在做insert和remove操作时,需要对数据项记录数字段递增或递减操作,虽然这算不上额外的开支
* 但是,在处理大量的插入和删除操作时,会影响性能。
* 操作:
* insert()
* remove()
* isEmpty()
* isFull()
* peekFront()或者front()
* peekRear()或者rear()
* display()
*
* 数据项记录数记录队列空和队列满的状态
*
* 数组实现,先进元素占数组下标从0开始到size-1的位置,再环绕
* 先出元素,从数组下标0开始,一直到front==size,再环绕
*
* 数组实现队列
* 有空间大小限制
* @Version 1.0
*/
public class QueueWithNItems {
public int[] array; //
public int rear; // 队尾
public int front; //队头
public int nItems; //数据项计数字段
public int size; // Queue大小
public QueueWithNItems(int size){
this.size = size;
this.front = 0; // 队头指针
this.rear = -1; //队尾指针
this.nItems = 0;
this.array = new int[this.size];
}
// 环绕处理
// 当rear指针超过size-1时,需要回到数组开始的地方,rear=-1
// 解决队列截断的问题,没有满却不能在插入数据项
// 在调用insert前,应该判断队列是否满
public void insert(int ele){
if(this.rear == this.size - 1){
this.rear = -1; //回绕开始的地方
}
this.array[++this.rear] = ele;
this.nItems++;// 数据项计数字段递增
}
// 移除元素
public int remove(){
int tmp = this.array[this.front++];
// 环绕处理,当队头指超过
if(this.front == this.size){
this.front = 0;
}
this.nItems--;
return tmp;
}
// 查看队头元素
public int front(){
return this.array[this.front];
}
// 查看队尾元素
public int<