1.定义队列类
public class arrayQueue {
private int MaxSize;//定义队列的最大容量
private int[] arr;//该数组用于存放数据表,模拟队列
private int rear;//rear指针,队列尾
private int front;//front指针,队列头的前一个数据
public Queue(int maxSize) {
MaxSize = maxSize;
//初始化数组
arr = new int[maxSize];
front = -1;
rear = -1;
}
}
2.arrayQueue中的一些方法
/**
* @return boolean
* @Author Mr.A
* @Description //TODO 判断队列是否已满
* @Date 11:25 2022/2/9
* @Param []
**/
public boolean isFull() {
if (rear == MaxSize - 1) {
return true;
} else
return false;
}
/**
* @return boolean
* @Author Mr.A
* @Description //TODO 判断队列是否为空
* @Date 11:30 2022/2/9
* @Param []
**/
public boolean isEmpty() {
if (rear == front) {
return true;
} else
return false;
}
/**
* @return void
* @Author Mr.A
* @Description //TODO 向队列中添加数据
* @Date 11:36 2022/2/9
* @Param [int]
**/
public void addQueue(int n) {
//首先判断队列是否已满,已满则补能添加数据
if (isFull() == true) {
System.out.println("队列已满,不能添加数据");
} else {
arr[rear + 1] = n;
rear++;
}
}
/**
* @return int
* @Author Mr.A
* @Description //TODO 从队列中取出数据
* @Date 11:41 2022/2/9
* @Param []
**/
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,不能取出数据");
}
front++;
return arr[front];
}
/**
* @return void
* @Author Mr.A
* @Description //TODO 显示队列
* @Date 11:36 2022/2/9
* @Param []
**/
public void showQueue() {
if (isEmpty() == true) {
System.out.println("队列是空的");
} else {
for (int i : arr) {
System.out.print(i + " ");
}
}
}
/**
* @Author Mr.A
* @Description //TODO 展示队列尾部元素
* @Date 16:03 2022/2/9
* @Param []
* @return int
**/
public int showRear(){
if(isEmpty()){
throw new RuntimeException("队列是空的");
}return arr[rear];
}
3.测试
public class queueTest {
public static void main(String[] args) {
Queue qu = new Queue(10);
qu.addQueue(5);
qu.showQueue();
qu.getQueue();
qu.addQueue(9);
qu.addQueue(10);
System.out.println(".............");
qu.showQueue();
System.out.println(".............");
System.out.println(qu.getQueue());
qu.showQueue();
System.out.println(qu.showRear());
}
}
4.测试结果
!!!学习笔记用,如有错误,还请指正。