实现思路:
实现的代码:
public class CircleQuenue {
private int maxSize;// 最大长度
private int[] arr; // 数组,存放值
private int font;// 队列头
private int rear;// 队列尾
public CircleQuenue(int arrMaxSize){
maxSize = arrMaxSize;
arr = new int[maxSize];
}
// 判断是否为空
public boolean isEmpty(){
return rear == font;
}
// 判断是否为满
public boolean isFull(){
return (rear + 1) % maxSize == font;
}
// 取出一个数据
public int getQuenue(){
if(isEmpty()){
throw new RuntimeException("为空。。");
}
int value = arr[font];
font = (font + 1) % maxSize;
return value;
}
// 添加一个数据
public void addQuenue(int n){
if(isFull()){
throw new RuntimeException("队列已满。。");
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
// 显示数据
public void showQuenue(){
if(isEmpty()){
throw new RuntimeException("队列为空。。");
}
for (int i = font; i < font + size() ; i++) {
System.out.printf("arr[%d]=%d\n",i % maxSize,arr[i%maxSize]);
}
}
// 得到队列的有效个数
public int size(){
return (rear + maxSize - font)%maxSize;
}
// 得到头指针
public int headQuenue(){
if(isEmpty()){
throw new RuntimeException("队列为空。。");
}
return arr[font];
}
}
简单的测试:
public static void main(String[] args) {
CircleQuenue quenue = new CircleQuenue(4);
System.out.println(quenue.isEmpty());
quenue.addQuenue(12);
quenue.showQuenue();
System.out.println(quenue.headQuenue());
System.out.println(quenue.getQuenue());
quenue.addQuenue(34);
quenue.addQuenue(23);
quenue.addQuenue(22);
quenue.showQuenue();
System.out.println(quenue.getQuenue());;
quenue.addQuenue(122);
quenue.showQuenue();
}