/*
- 思路:
-
- front 变量的含义做一个调整:front 就指向队列的第一个元素,也就是说array【front】
- 就是第一个元素front的初始值 = 0;
- 2.rear变量 的含义做一个调整:rear指向对流的最后一个元素的后一个位置,因为希望空
- 粗怀一个空间做约定
- 3.当队列满时,条件时(rear+1)%maxsize == front (满)
- 4.当队列为空时:rear == front
- 5.队列的有效的数据个数:(rear+maxSize- front)%maxsize
- 数组模拟环形队列
*/
package com.hadwinling.queue;
import java.util.Scanner;
public class ArrayQueueDemo02 {
public static void main(String[] args) {
CircleArray circleArray = new CircleArray(4);//说明设置4,其队列的有效数据最大是3
char key ;//接受用户输入
Scanner input = 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 = input.next().charAt(0);
switch (key) {
case 's':
circleArray.showQueue();
break;
case 'e':
loop = false;
break;
case 'a':
System.out.println("请输入一个数");
int value = input.nextInt();
circleArray.addQueue(value);
break;
case 'g':
try {
int res = circleArray.getQueue();
System.out.println("取出的数据是:"+ res);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = circleArray.headQueue();
System.out.println("队列头信息:"+res);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
circleArray.showQueue();
break;
default:
break;
}
}
}
}
class CircleArray{
private int maxSize;//表示数组的最大容量
//front 变量的含义做一个调整:front 就指向队列的第一个元素,也就是说array【front】
//就是第一个元素front的初始值 = 0;
private int front ;//队列头
//2.rear变量 的含义做一个调整:rear指向对流的最后一个元素的后一个位置,因为希望空
//存放一个空间做约定
private int rear;//队列尾
private int[] array;//该数据用于存放数据,模拟队列
/**
*
*/
public CircleArray(int arrayMaxSize) {
maxSize = arrayMaxSize;
array = 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;
}
//直接将数据加入
array[rear] = n;
//将rear后移,必须考虑去后
rear = (rear+1)%maxSize;
}
//获取队列的数据,出队列
public int getQueue() {
//判断队列是否为空
if (isEmpty()) {
//通过抛出异常
throw new RuntimeException("队列为空,不能取数据");
}
//这里需要分析出front是指向队列的第一个元素
//1.先把front对应的值保留到一个临时变中
//2.将front后移,考虑取模
//3.将临时保存的变量返回
int value = array[front];
front = (front+1)%maxSize;
return value;
}
//显示队列的所有数据
public void showQueue() {
//遍历
if (isEmpty()) {
System.out.println("队列为空,没有数据");
return;
}
//思路:从front开始遍历,遍历多少个元素
for (int i = front; i < front+size(); i++) {
System.out.println(i%maxSize+"\t"+ array[i%maxSize]);
}
}
//求出当前队列有效数据的个数
public int size() {
//eg:
//rear = 2;
//front = 1;
//maxsize = 3;
return (rear+maxSize-front) % maxSize;
}
//显示队列的头数据
public int headQueue() {
//判断
if (isEmpty()) {
throw new RuntimeException("队列为空,没有数据");
}
return array[front];
}
}