package queue;
import java.util.Scanner;
public class CircleArrayQueue {
public static void main(String[] args) {
System.out.println("测试数组模拟环形队列的案例~~~");
CircleArrayQueueClass queue = new CircleArrayQueueClass(5);
char key = ' ';
Scanner scanner = 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("o(out): 从队列取出数据");
System.out.println("g(get): 查看队列头的数据");
key = scanner.next().charAt(0);
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("输出一个数");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'o':
try {
int res = queue.outQueue();
System.out.printf("取出的数据是%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("队列头的数据是%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出~~");
}
}
class CircleArrayQueueClass{
private int[] arr;
private int front;
private int rear;
private int MAXSIZE;
public CircleArrayQueueClass(int MAXSIZE) {
this.MAXSIZE=MAXSIZE;
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 x) {
if(isFull()) {
throw new RuntimeException("full");
}
arr[rear++]=x;
System.out.println("add sucess");
}
public int outQueue() {
if(isNull()) {
throw new RuntimeException("null");
}
return arr[front++];
}
public void showQueue() {
if(isNull()) {
System.out.println("null");
}else {
if(front>rear) {
for(int i=front;(i+1)%MAXSIZE<=rear;) {
System.out.printf("%d\t",arr[i]);
i=(i+1)%MAXSIZE;
}
}else if(front<rear) {
for(int i=front;i<rear;i++) {
System.out.printf("%d\t",arr[i]);
}
}
}
System.out.println();
}
public int numQueue() {
return (rear-front+MAXSIZE)%MAXSIZE;
}
public int getQueue() {
return arr[front];
}
}