1.队列
首先我们知道队列是尾进头出,所以如果我们用数组实现队列会出现一下这种情况。
这时候我们想要插入就不行了,会数组溢出,但是不插入又会浪费两格空间。所以这时候就有了循环队列。
2.循环队列
如图把数组假象成一个环,为了方便判断环 是否 满 和 空,空出一个位置(可以对比最右边队满的两幅图),这样就可以根据公式:
rear=front 判断是否为空
(rear+1)%maxSize==front 判断是否为满
队空 队列只有一个元素 队满
队满(此时队列里值为45,54,78) 队列只有一个元素 队空
3代码
package com.hyh.datastructure;
public class CQueue {
private int front;//指向队首
private int rear;//指向队尾
private int[] elem;
private int maxSize;//最大容量
public CQueue(int maxSize) {
this.front = 0;
this.rear = 0;
this.elem = new int[maxSize];
this.maxSize = maxSize;
}
public boolean isEmpty(){
return rear==front;
}
public boolean isFull(){
return (rear+1)%maxSize==front;
}
public void offer(int val){
if(isFull())return;
elem[rear++]=val;
rear=rear%maxSize;
}
public void poll(){
if(isEmpty())return;
front=++front%maxSize;
}
public int peek(){
if(isEmpty())return -1;
return elem[front];
}
@Override
public String toString() {
String str="";
for (int i:elem
) {
str=str+i;
}
return str;
}
public static void main(String[] args) {
CQueue c= new CQueue(5);
System.out.println(c.isEmpty());//true
for (int i = 0; i < 5; i++) {
c.offer(i);
}
System.out.println(c.isFull());//true
System.out.println(c.toString());//01230 因为实际容量是maxSize-1 所以只存了前4次的值
c.poll();
c.offer(4);
System.out.println(c.toString());//01234
c.poll();
c.offer(5);
System.out.println(c.toString());//51234
}
}