class ArrayQueue
package DataStructures.queue;
/**
* @author coffee
* @date 2021-03-29 15:55
*/
public class ArrayQueue {
private int maxSize;//队列最大容量
private int front; //头
private int rear;//尾
private int[] arr;//模拟队列的数组
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
front = -1;//指向队列第一个元素的前一个位置
rear = -1;
arr = new int[maxSize];
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull(){
return rear == maxSize - 1;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty(){
return rear == front;
}
/**
* 添加数据到队列
* @param n
*/
public void addQueue(int n){
//判断队列是否已满
if (isFull()){
System.out.println("队列已满");
return;
}
//让rear后移
rear++;
arr[rear] = n;
}
/**
* 获取队列的数据,出队列
* @return
*/
public int getQueue(){
//判断队列是否为空
if (isEmpty()){
//通过抛出异常
throw new RuntimeException("队列为空");
}
//front后移
front++;
return arr[front];
}
/**
* 显示队列的所有数据
*/
public void showQueue(){
//判断是否为空
if (isEmpty()){
System.out.println("队列为空");
return;
}
//遍历
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "/t");
}
}
/**
* 显示队列的头数据
* @return
*/
public int headQueue(){
//判断是否为空
if (isEmpty()){
throw new RuntimeException("队列为空");
}
return arr[front + 1];
}
}
队列加强版
class ArrayQueuePlus
package DataStructures.queue;
/**
* @author coffee
* @date 2021-03-29 16:39
*/
public class ArrayQueuePlus {
private int maxSize;//队列最大容量
private int front; //头
private int rear;//尾
private int[] arr;//模拟队列的数组
public ArrayQueuePlus(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull(){
return (rear + 1) % maxSize == front;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty(){
return rear == front;
}
/**
* 添加数据到队列
* @param n
*/
public void addQueue(int n){
//判断队列是否已满
if (isFull()){
System.out.println("队列已满");
return;
}
arr[rear] = n;
//让rear后移
rear = (rear + 1) % maxSize;
}
/**
* 获取队列的数据,出队列
* @return
*/
public int getQueue(){
//判断队列是否为空
if (isEmpty()){
//通过抛出异常
throw new RuntimeException("队列为空");
}
//front后移
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.print("arr["+ i % maxSize + "]=" + arr[i % maxSize] + "/t");
}
}
/**
* 显示队列的头数据
* @return
*/
public int headQueue(){
//判断是否为空
if (isEmpty()){
throw new RuntimeException("队列为空");
}
return arr[front];
}
/**
* 求出当前队列有效数据个数
* @return
*/
public int size(){
return (rear + maxSize - front) % maxSize;
}
}