1.介绍
队列只允许在一端进行插入操作,而在另一端进行删除操作,是有序列表,遵循先进先出
2.代码实现
2.1 数组模拟队列
//数组模拟队列
public class ArrayQueue {
private int maxSize;//数组最大容量
private int front;//队列头指针
private int rear;//队列尾指针
private int[] arr;//模拟队列
//创建队列
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
//判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
//判断队列是否为空
public boolean isEmpty() {
return front == rear;
}
//添加数据
public void addQueue(int n) {
if(isFull()) {
throw new RuntimeException("队列满,不能添加数据");
}
rear++;
arr[rear] = n;
}
//获取队列的数据,出队列
public int getQueue() {
if(isEmpty()) {
throw new RuntimeException("队列空,不能取数据");
}
front++;
return arr[front];
}
//显示队列所有的数据
public void showQueue() {
if(isEmpty()) {
throw new RuntimeException("队列空");
}
for(int i : arr) {
System.out.print(i + "\t");
}
}
//显示队列的头数据,但并不取出
public int headQueue() {
if(isEmpty()) {
throw new RuntimeException("队列为空");
}
return arr[front + 1];
}
}
2.2 数组模拟循环队列
class CircleArray {
private int maxSize;//数组最大容量
private int front;//队列头指针
private int rear;//队列尾指针,指向队列最后一个元素的后一个位置,为了方便区分空队列和满队列
//故maxSize长度的数组只能存maxSize-1个数据
private int[] arr;//模拟队列
public CircleArray(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[this.maxSize];
front = 0;
rear = 0;
}
//判断队列是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
//判断队列是否为空
public boolean isEmpty() {
return front == rear;
}
//添加数据
public void addQueue(int n) {
if(isFull()) {
throw new RuntimeException("队列满,不能存数据");
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
//获取队列的数据,出队列
public int getQueue() {
if(isEmpty()) {
throw new RuntimeException("队列空,不能取数据");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
//显示队列所有的数据
public void showQueue() {
if(isEmpty()) {
throw new RuntimeException("队列空");
}
for(int i = front; i < front + size(); i++) {
System.out.print("arr[" + i % maxSize + "]" + arr[i % maxSize] + "\t");
}
}
//求出当前队列有效数据的个数
public int size() {
return (rear + maxSize - front) % maxSize;
}
//显示队列的头数据,但并不取出
public int headQueue() {
if(isEmpty()) {
throw new RuntimeException("队列为空");
}
return arr[front];
}
}