public class CircleArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
//创建队列的构造器
public CircleArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = 0;//front指向的是队列的第一个位置的前一个位置
rear = 0;//当队列中有值的时候,那么我们的数组下表其实就是rear。就是队列的最后一个数据。
}
public Boolean isFull() {
return (rear + 1) % maxSize == front;
}
public Boolean isEmpty() {
return rear == front;
}
/**
* 添加数据
*/
public void addQueue(int n) {
//首先判断是否满了
if (isFull()) {
System.out.println("链表已经满了");
return;
}
//加入数据吧
arr[rear] = n;
// rear++;这样的情况是在rear还不是最后一个元素的时候
//要是rear指向maxSize -1的话,如果直接加一,就会出现数组越界异常了。
//因此,我们把他重新指向第一个元素的位置。
//取余的运算规则要牢牢记住
rear = (rear + 1) % maxSize;
}
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,滚!");
}
//取数据的时候,我们只需要变化front。
int temp = arr[front];
front = (front + 1) % maxSize;
return temp;
}
//显示队列的所有数据吧
public void showQueue() {
//首先判断队列是否为空
if (isEmpty()) {
System.out.println("队列是空的");
return;
}
for (int i = front; i < front + ((rear - front + maxSize) % maxSize); i++) {
System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
}
}
public int size() {
return (rear - front + maxSize) % maxSize;
}
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空,没有数据");
}
return arr[front];
}}
环形数组11
最新推荐文章于 2023-03-16 10:41:39 发布