一、实现思路
1、创建实现类(circleQueueArray)
2、在实现类里面写入以下方法
front = rear = 0;
(1)向队列添加数据
rear = (rear + 1) % MaxSize
(2)从队列取出数据
front = (front + 1) % MaxSize
(3)展示队列
注意:
循环队列的有效长度为:
(rear + MaxSize -front)% MaxSize
(4)取出头元素数据
头元素就是front所指的值
二、实现
1.运行结果
2.实现代码
代码如下(示例):
import java.util.Scanner;
public class CircleArrayQueueDemo {
public static void main(String[] args) {
CircleArrayQueue queue = new CircleArrayQueue(4); // 实际有数字3
Scanner sc = new Scanner(System.in);
boolean loop = true;
while(loop){
System.out.println("1.a(add)入队");
System.out.println("2.g(get)出队");
System.out.println("3.s(show)展示队列");
System.out.println("4.h(head)得到队头元素");
System.out.println("5.e(exit)退出");
System.out.println("请选择您的操作:");
char command = sc.next().charAt(0);
switch(command){
case 'a':
System.out.println("请输入需要添加的数据:");
int value = sc.nextInt();
queue.addQueue(value);
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("%d已出队\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 's':
queue.showQueue();
break;
case 'h':
try {
System.out.println("队头元素是:"+queue.headQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
sc.close();
loop = false;
break;
default:
System.out.println("请输入正确的命令~~");
}
}
System.out.println("退出程序~~");
}
}
class CircleArrayQueue{
private int MaxSize;
private int front;
private int rear;
private int[] arr;
public CircleArrayQueue(int arrMaxSize){
MaxSize = arrMaxSize;
arr = new int[MaxSize];
//front = rear = 0; // 默认
}
// 判断队列是否为空
public boolean isEmpity(){
return front == rear;
}
// 判断队列是否满
public boolean isFull(){
return (rear + 1) % MaxSize == front;
}
// 入队
public void addQueue(int a){
if(isFull()){
System.out.println("队列已满,不能再添加了");
return;
}
arr[rear] = a;
rear = (rear + 1) % MaxSize;
}
// 出队
public int getQueue(){
if(isEmpity()){
throw new RuntimeException("队列为空,不能出队~~");
}
int value = arr[front];
front = (front + 1) % MaxSize;
return value;
}
// 展示队列
public void showQueue(){
if(isEmpity()){
System.out.println("队列为空~~");
return;
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d]=%d\n" , i % MaxSize, arr[i % MaxSize]);
}
}
// 得到有效长度
public int size(){
return (rear + MaxSize - front) % MaxSize;
}
// 得到队头元素
public int headQueue(){
if (isEmpity()){
throw new RuntimeException("队列为空,没有队头元素~~");
}
return arr[front];
}
}