队列:
队列是一个有序列表,可以用数组和链表实现 遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的数据要后取出。 队列的实现方式有两种: 一种是数组模拟队列,一种是链表模拟队列
环形数组队列代码实现:
public class CircleArrayQueue {
public static void main(String[] args) {
System.out.println("测试循环数组队列!~~~~");
CircleQueue circleQueue = new CircleQueue(4);
boolean loop = true;
Scanner scanner = new Scanner(System.in);
char key = ' ';//用于接收用户输入
//菜单
while (loop) {
System.out.println("a(add):添加元素到队列中");
System.out.println("g(get):获取元素");
System.out.println("s(show):遍历队列");
System.out.println("h(head):获取队列中第一个元素");
System.out.println("e(exit):退出程序");
System.out.println();
System.out.println("请输入要进行的操作");
key = scanner.next().charAt(0);
switch (key) {
case 'a':
System.out.println("请输入要添加的数据");
int value;
try {
value = scanner.nextInt();
circleQueue.addQueue(value);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 'g':
int res = circleQueue.getQueue();
System.out.println(res);
break;
case 's':
circleQueue.showQueue();
break;
case 'h':
int head = circleQueue.headQueue();
System.out.println(head);
break;
case 'e':
scanner.close();
loop = false;
default:
break;
}
}
System.out.println("程序退出~~");
} }
/** * 循环数组队列 */ class CircleQueue {
private int front; //循环队列的头部
private int rear; //循环队列尾部
private int maxSize; //数组的长度
private int[] arr; //数组
public CircleQueue(int arrMaxSize) {
front = 0;// 初始值为0, 队列的第一个元素
rear = 0; //初始值为0, 队列中最后一个元素的后一个位置
maxSize = arrMaxSize;
arr = new int[maxSize]; //初始化数组
}
//判断队列是否为空
public boolean isEmpty() {
return rear == front;
}
//判断队列是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
//添加元素
public void addQueue(int n) {
//首先判断队列是否满了,如果满了 就不能再添加元素,如果没满,可以添加元素
if (isFull()) {
System.out.println("队列已满,不能添加元素~~");
return;
}
//错误:rear = (rear + 1) % maxSize;
//错误:arr[rear] = n;
//添加数据直接添加,因为rear指向当前位置的后一个位置
arr[rear] = n;
//添加完之后,需要移动rear的位置
rear = (rear + 1) % maxSize;
}
//获取元素
public int getQueue() {
//首先判断队列是否为空
if (isEmpty()) {
throw new RuntimeException("队列为空,不能获取元素~~");
}
//1.获取元素,之前我要先将值存入一个临时变量
//2.移动front
//3.获取临时变量的值
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
//获取队列中的元素
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空,不能遍历队列!~");
return;
}
for (int i = front; i < front + size(); i++) {
//这边的索引是什么 动脑筋 ,索引出来,元素也就出来了
//标记:自己写的错误 System.out.printf("arr[%d]=%d\n", i % maxSize, i % maxSize);
System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
}
}
//获取队列头部的元素
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,头部没有元素!");
}
// TODO: 2020/10/24 自己写的错误 return front % maxSize;
return arr[front];
}
//获取队列中有效的数据个数
public int size() {
//标记:自己写错的地方:return (front + maxSize - rear) % maxSize; // front=0 rear =1 maxSize=3 return 1
return (rear + maxSize - front) % maxSize;
} } ```