数组模拟环形队列
思路如下:
1.front 变量的含义做一个调整: front 就指向队列的第一个元素, 也就是说arr[front]就是队列的第一个元素 front的初始值=0
2. rear变量的含义做一个调整: rear指向队列的最后一个元素的后一个位置.因为希望空出一个空间做为约定. rear的初始值=0
3.当队列满时,条件是(rear +1) % maxSize= front[满]
4.对队列为空的条件,rear== front空
代码演示
public class CircleArrayDemo {
public static void main(String[] args) {
System.out.println("测试数组模拟环形队列");
//给的长度是4 但是实际长度为3 之前预留一个位置
CircleArray arrayQueue = new CircleArray(4);
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("g(get):从队列取出数据");
System.out.println("h(head):查看队头数据");
//接收一个字符
key = scanner.next().charAt(0);
switch (key) {
case 's':
arrayQueue.showQueue();
break;
case 'a':
System.out.println("请输入一个数");
int value = scanner.nextInt();
arrayQueue.addQueue(value);
break;
case 'g':
try {
int queue = arrayQueue.getQueue();
System.out.println("取出的数据是:" + queue);
} 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) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'e': //退出
scanner.close();
loop = false;
break;
default:
break;
}
}
}
static class CircleArray {
private int maxSize;//数组最大容量
private int front;//队列头 初始值为0
private int rear;//队列尾 初始值为0
private int arr[];//用于存放数据,模拟队列
//创建队列的构造器
public CircleArray(int arraySize) {
maxSize = arraySize;
arr = new int[maxSize];
rear = 0;
front = 0;
}
//判断队列是否满
public boolean isFull() {
//如果是返回true,不是返回false
return (rear + 1) % maxSize == front;
}
//判断队列是否为空
public boolean isEmpty() {
if (rear == front) return true;
else return false;
}
//入队
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列满,不能加入数据");
return;
}
//直接将数据加入
arr[rear] = n;
//将rear后移,这里必须考虑取模
//
rear = (rear + 1) & maxSize;
}
//出队
public int getQueue() {
if (isEmpty()) {
//通过抛出异常 throw也有return的意思
throw new RuntimeException("队列空,不能取数据");
}
//这里需要分析出front是指向队列的第- -个元素
//1.先把front对应的值保留到一个临时变量
//2.将front后移
//3.将临时保存的变量返回
int temp = arr[front];
//防止越界
front = (front + 1) & maxSize;
return temp;
}
//显示队列的所有数据
public void showQueue() {
if (isEmpty()) {
System.out.println("队列空,没有数据");
return;
}
for (int i = front; i < getSize(); i++) {
System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
}
}
//求出当前队列有效数的个数
public int getSize() {
return (rear + maxSize - front) % maxSize;
}
//显示队列的头数据,注意不是取出数据
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空,没有数据");
}
return arr[front];
}
}
}