思路如下:
- front变量的含义做一个调整:front就指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素,front的初始值为0。
- rear变量的含义做一个调整:rear指向队列的最有一个元素的后一个位置,因为希望空出一个空间作为约定,rear的初始值为0。
- 当队列满时,条件是(rear+1)%maxsize=front。
- 队列为空的条件是:front==rear。
- 队列中有效数据的个数:(rear+maxSize-front)%maxSize
代码调整如下:
import java.util.Scanner;
public class circleArrayQueue {
public static void main(String[] args) {
circleArray arrayQueue= new circleArray(3);
char key = ' ';
Scanner input = new Scanner(System.in);
boolean loop = true;
while(loop) {
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出程序");
System.out.println("a(add):添加数据到队列");
System.out.println("g(get):从队列取出数据");
System.out.println("h(head):查看队列头的数据");
key = input.next().charAt(0);
switch(key) {
case 'a'://添加数据
System.out.println("输入一个数据");
int value = input.nextInt();
arrayQueue.addQueue(value);
break;
case 's'://展示数据
arrayQueue.show();
break;
case 'g'://取出数据
try {
int res = arrayQueue.getQueue();
System.out.printf("取出的数据是%d\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h'://查看队列头的数据
try {
int res =arrayQueue.headQueue();
System.out.printf("头数据是%d\n",res);
} catch (Exception e) {
System.out.println(e.hashCode());
}
break;
case 'e'://退出
input.close();
loop=false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class circleArray{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public circleArray(int arrMaxSize) {
maxSize=arrMaxSize;
arr = new int[maxSize];
}
public boolean isFull() {
return (rear+1)%maxSize==front;
}
public boolean isEmpty() {
return rear==front;
}
public void addQueue(int n) {
if(isFull()) {
System.out.println("队列满不能加入数据");
return;
}
arr[rear]=n;
System.out.println("arr[rear]="+arr[rear]);
rear=(rear+1)%maxSize;
}
public int getQueue() {
if(isEmpty() ) {
throw new RuntimeException("队列空,不能取数据");
}
int value = arr[front];
front=(front+1)%maxSize;
return value;
}
public void show() {
if(isEmpty()) {
System.out.println("队列空没有数据");
return;
}
for(int i=front;i<front+(rear+maxSize-front)%maxSize;i++) {
System.out.println("arr["+i%maxSize+"]="+arr[i%maxSize]);
}
}
public int headQueue() {
if(isEmpty() ) {
throw new RuntimeException("队列空,不能取数据");
}
return arr[front];
}
}