提示:看了老师视频有些疑惑:这里我自己看法
主要参考了尚硅谷韩老师视频和大话数据结构p115
一、直接上代码
package com.QueueStudy;
public class CircleArrayQueue {
private int maxSize;//表示数组的最大容量
private int front;//指向队列头
private int rear;//队列尾的下一个元素
private int[] arr;//该数据用于存放数据,模拟队列
public CircleArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[maxSize];
front = 0;//指向队列头部,分析出front是指向队列头的前一个位置。
rear = 0;//指向队列尾,指向队列尾的数据(即就是队列最后一个数据)
}
//判断队列是否满
public boolean ifFull(){
return (rear + 1)%maxSize == front;
}
//判断队列是否为空
public boolean isEmpty(){
return rear == front;
}
//添加数据到队列
public void addQueue(int n){
if (ifFull()){
System.out.println("队列满,不能加入数据");
return;
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
//获取队列的数据,出队列
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列空,不能取出数据");
}
int temp = arr[front];
front = (front + 1) % maxSize;
return temp;
}
//显示队列的所有数据
public void show(){
if (isEmpty()){
System.out.println("队列空的,没有数据");
}
for (int i = front;i < front + getSize();i++){
System.out.print(arr[i % maxSize] + " ");
}
}
//显示队列的头数据,注意不是取出数据
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列空的,没有数据");
}
return arr[front];
}
public int getSize(){
return (rear - front + maxSize)%maxSize;
}
}
class QueueTest(){
@Test
public void testCircleArrayQueue(){
CircleArrayQueue queue = new CircleArrayQueue(3);
queue.addQueue(1);
queue.addQueue(2);
//注意这时候数组还有1个空位置,但是这时候我们约定数组已经满了
int queueQueue = queue.getQueue();
System.out.println("获取1个元素 " + queueQueue);
//把3插入下表2数组中 数组0空
queue.addQueue(3);
queue.show();
}
}
总结
这是我自己一些看法
内容参考尚硅谷韩老师数据结构与算法
代码注释中参考大话数据结构p115



