队列的实现方式可以通过链表和数组,大多数是链表,但是在使用中有不少要求使用数组的数据结构,抱着好奇的心态写了如下数据结构及其相关的方法
/**
* @author zy
* @date 2020/6/17 19:31
*/
public class ArrayQueue {
/*
长度为maxSize-1
*/
private int maxSize;
private int rear;
private int front;
private int[] arr;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.front = 0;
this.rear = 0;
this.arr = new int[maxSize];
}
public boolean isFull(){
if ((rear+1) % maxSize == front) {
return true;
} else
return false;
}
public boolean isEmpty(){
return front == rear;
}
public boolean enQueue(int data){
if(this.isFull()){
throw new RuntimeException("队列已满");
}
arr[rear] = data;
rear = (rear+1)%maxSize;
System.out.println(rear);
return true;
}
public int deQueue(){
if(this.isEmpty()){
throw new RuntimeException("队列为空");
}
int val = arr[front];
front = (front+1)%maxSize;
return val;
}
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(2);
arrayQueue.enQueue(1);
arrayQueue.enQueue(2);
System.out.println(arrayQueue.isFull());
}
}
主要运用了取余的思想使整个队列联系了起来,通过游标的移动解决了问题