- front 变量的含义做一个调整:front就指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素。
front的初始值为0;
- rear变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定。rear 的初始值为0;
- 当队列满时,条件是
(rear + 1)%maxSize == front 此时满。
- 当队列为空的条件,
rear == front 空
- 当这样分析后,此时队列中有效的数据的个数是
(rear + maxSize - front)%maxSize //rear=1 front=0
- 以上我们就可以按照我们的思路对原来的代码进行修改。
import java.util.Scanner;
public class 队列 {
public static void main(String[] args) {
System.out.println("测试数组模拟循环队列的案例~~~");
CircleArray aq=new CircleArray(4);
char key = ' ';
Scanner sc = 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 = sc.next().charAt(0);
switch(key) {
case 's':
aq.showQueue();
break;
case 'a':
System.out.println("请输入一个数");
int value = sc.nextInt();
aq.addQueue(value);
break;
case 'g':
try {
int res = aq.getQueue();
System.out.printf("取出的数据实%d\n",res);
aq.getQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = aq.headQueue();
System.out.printf("取出的数据实%d\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 'e':
sc.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];
front = 0;
rear = 0;
}
public boolean isFull() {
return (rear + 1)%maxSize == front;
}
public boolean isNull() {
return rear == front;
}
public void addQueue(int n) {
if(isFull()) {
System.out.println("队列满,不能加入数据");
return;
}
arr[rear] = n;
rear = (rear+1) % maxSize;
}
public int getQueue() {
if(isNull()) {
throw new RuntimeException("队列为空,不能获取数据");
}
int value = arr[front];
front = (front +1 ) % maxSize;
return value;
}
public void showQueue() {
if(isNull()) {
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(isNull()) {
throw new RuntimeException("队列空,没有数据");
}
return arr[front];
}
}