class ArrayQueue {
// 设置指针指向队列头部的前一个位置
private int front = -1;
// 设置指针指向队列的尾部
private int rear = -1;
// 设置队列的最大容量
private int maxSize;
// 用于存放数据模拟队列的数组
private int[] arr;
public ArrayQueue(int maxSize){
this.maxSize = maxSize;
this.arr = new int[maxSize];
}
/**
* 用于添加数据进队列
* @param n
*/
public void add(int n){
if (ifFull()){
System.out.println("队列已满!");
return;
}
rear++;
arr[rear] = n;
}
/**
*
* @return
*/
public int get(){
if (ifEmpty()){
throw new RuntimeException("队列为空!");
}
front++;
return arr[front];
}
/**
* 显示队列
*/
public void show(){
if (ifEmpty()){
System.out.println("队列是空的!");
return;
}
for (int i = front+1; i<= rear; i++){
System.out.printf(arr[i] + "\t");
}
System.out.println();
}
/**
* 显示头部数据
*/
public void showHead(){
System.out.println(arr[front+1]);
}
/**
*
* @return rear
*/
public boolean ifFull(){
return rear == maxSize-1;
}
/**
* 用于判断队列是否为空
* @return
*/
public boolean ifEmpty(){
return front == rear;
}
}
2.3.2 数组模拟环形队列
class ArrayQueue2 {
// 设置队列最大容量
private int maxSize;
// 设置指针指向队列头部位置
private int front;
// 设置指针指向队列尾部的后一个位置
private int rear;
private int[] arr;
public ArrayQueue2(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[maxSize];
}
public boolean isFull(){
return (rear+1) % maxSize == front;
}
public boolean isEmpty(){
return rear == front;
}
public void add(int n){
if (isFull()){
System.out.println("队列已满!");
return;
}
arr[rear] = n;
rear = (rear+1) % maxSize;
}
public int get(){
if (isEmpty()){
throw new RuntimeException("队列为空!");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
public int showHead(){
if (isEmpty()){
throw new RuntimeException("队列为空");
}
return arr[front];
}
public void show(){
if (isEmpty()){
System.out.println("队列为空...");
return;
}
for (int i = front; i < front + size();i++){
System.out.println(arr[i % maxSize]);
}
}
public int size(){
return (rear+maxSize-front) % maxSize;
}
}