public class CircleArrayQueueDemo {
public static void main(String[] args) {
System.out.println("测试模拟环形队列的案例~");
CircleArrayQueue queue = new CircleArrayQueue(4);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while(loop){
System.out.println("s:显示队列");
System.out.println("e:退出程序");
System.out.println("a:添加数据到队列");
System.out.println("g:从队列取出数据");
System.out.println("h:查看队列头的数据");
key = scanner.next().charAt(0);
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("请输入一个数:");
int num = scanner.nextInt();
queue.addQueue(num);
break;
case 'g':
try {
int result = queue.getQueue();
System.out.printf("取出的数据是%d\n",result);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int result = queue.headQueue();
System.out.printf("队列头的数据是%d\n",result);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class CircleArrayQueue{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public CircleArrayQueue(int maxSize){
this.maxSize = maxSize;
this.arr = new int[maxSize];
this.front = 0;
this.rear = 0;
}
public boolean isFull(){
return (this.rear + 1) % this.maxSize == this.front;
}
public boolean isEmpty(){
return this.rear == this.front;
}
public void addQueue(int num){
if(isFull()){
System.out.println("队列已满,请稍后再添加。");
return;
}
this.arr[this.rear] = num;
this.rear = (this.rear + 1) % this.maxSize;
}
public int getQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空,不能取数据。");
}
int value = this.arr[this.front];
this.front = (this.front + 1) % this.maxSize;
return value;
}
public void showQueue(){
if(isEmpty()){
System.out.println("队列为空。");
return;
}
for (int i = this.front; i < this.front + size(); i++) {
System.out.printf("arr[%d]=%d\n", i % this.maxSize,arr[i % this.maxSize]);
}
}
public int size(){
return (this.rear + this.maxSize - this.front) % this.maxSize;
}
public int headQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空。");
}
return this.arr[this.front];
}
}