1.队列介绍
1)队列是一个有序列表,可以用数组或是链表实现。
2)遵循先进先出原则。即:先存入列表的数据,先取出。后存入的后取出
2.数组模拟循环队列思路
1)队列的输出、输入时分别从前后两端来处理,因此需要两个变量front(队头)及rear(队尾)来实现输入及输出。
2)front初始值=0;front指向队列的第一个元素。
3)rear的初始值=0;rear指向队列的最后一个元素的后一个位置。因此队列的最大容量比数组的长度少1。
4)队列满的条件为(rear+1)%array.length(数组长度)==front。
5)队列空的条件为front==rear。
6)队列中有效数据的个数**(rear+array.length-front)%array.length**。
代码实现
public class CricleArrayQueue {
private int[] array;
//队头
private int front;
//队尾
private int rear;
//创建数组
public CricleArrayQueue(int maxSize){
this.array=new int[maxSize];
}
//判断队列是否满
public boolean isFull(){
if((rear+1)%array.length==front){
return true;
}
return false;
}
//判断队列是否空
public boolean isEmpty(){
if(front==rear){
return true;
}
return false;
}
//求出队列中有效数据个数
public int size(){
return (rear+array.length-front)%array.length;
}
//入队
public void addQueue(int element)throws Exception{
if(isFull()){
throw new Exception("队列已满");
}
array[rear]=element;
//队尾往下移一位
rear=(rear+1)%array.length;
}
//出队
public int deQueue() throws Exception{
if(isEmpty()){
throw new Exception("队列已空");
}
int deQueueElement=array[front];
front=(front+1)%array.length;
return deQueueElement;
}
//输出有效队列
public void outPut(){
//先判断是否为空队列
if(isEmpty()){
System.out.println("队列为空,无法输出");
return;
}
//把队列想成一个环
//那么front+size()为输出个数!
for(int i=front;i<front+size();i++){
System.out.println(array[i%array.length]);
}
}
}
测试代码
//测试
public static void main(String[] args) {
CricleArrayQueue queue=new CricleArrayQueue(4);
System.out.println("队列个数为:"+queue.size());
queue.outPut();
try{
queue.addQueue(23);
queue.addQueue(24);
queue.addQueue(87);
queue.addQueue(34);
}catch(Exception e){
System.out.println(e.getMessage());
}
try{
queue.deQueue();
queue.deQueue();
queue.deQueue();
}catch(Exception e){
System.out.println(e.getMessage());
}
try{
queue.addQueue(34);
queue.addQueue(37);
}catch(Exception e){
System.out.println(e.getMessage());
}
queue.outPut();
System.out.println("队列个数为:"+queue.size());
}
结果如下: