本篇只是日记不做过多的讲解,不明白公式
(rear+1)%maxsize==front,
(rear-front+maxsize)%maxsize
如何推导请移步(2条消息) 循环队列中公式的推导,原理,超详解_星空的你的博客-优快云博客
代码如下:
import java.util.Scanner;
public class CircleQueueDemo {
public static void main(String[] args) {
CircleQueue queue=new CircleQueue(3);
Scanner scan=new Scanner(System.in);
boolean loop=true;
while(loop){
System.out.print("请输入命令:");
char key=scan.next().charAt(0);
switch (key){
case 'a':
try {
System.out.print("输入要添加的数:");
int n=scan.nextInt();
queue.addQueue(n);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int elem=queue.getQueue();
System.out.println("已取出元素:"+elem);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 's':
try {
queue.showQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
queue.headQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scan.close();
loop=false;
System.out.println("程序退出!");
break;
default:
break;
}
}
}
}
class CircleQueue{
private int maxsize;
private int front;
private int rear;
private int[] arr;
public CircleQueue(int maxsize){
this.maxsize=maxsize;
arr=new int[maxsize];
front=0;
rear=0;
}
public boolean isFull(){
return (rear+1)%maxsize==front;
}
public boolean isEmpty(){
return front==rear;
}
public void addQueue(int n){
if(isFull()){
throw new RuntimeException("添加失败,队已满~");
}
arr[rear++]=n;
rear=rear%maxsize;
}
public int getQueue(){
if(isEmpty()){
throw new RuntimeException("取出失败,队已空~");
}
int n=arr[front++];
front=front%maxsize;
return n;
}
public void showQueue(){
if(isEmpty()){
throw new RuntimeException("无法显示,队已空~");
}
for (int i = 0; i <(rear-front+maxsize)%maxsize ; i++) {
System.out.println(arr[(front+i)%maxsize]);//此处需要特别注意
}
}
public void headQueue(){
if(isEmpty()){
throw new RuntimeException("无法显示,队已空~");
}
System.out.println(arr[front]);
}
}