计算:
- 环形数组的指针下标的计算为 (指针下标 + 步长) % 数组长度
- 队列中元素个数:(rear - front + m) % m
- 队列剩余位置(此处把保留的辅助空位也算进去了):(front - rear + m) % m
关键:保留一个空位,以便区分队列是空还是满
核心:入队出队是指针的移动,根据指针下标判断队列的存储情况
- 入队:rear = (rear + 1) % n ;
- 出队:front = (front + 1) % n ;
- 队空:front == rear ;
- 队满(rear后移一位与front重叠 —>把空位补上之后队满):(rear + 1) % n == front ;
public class CircleArrTest {
public static void main(String[] args) {
//1.获取键盘数据
Scanner scan = new Scanner(System.in);
char c;
boolean flag = true;
CircleArray circleArray = new CircleArray(4);
while (flag){
System.out.println("s(show): 显示队列");
System.out.println("e(exit): 退出程序");
System.out.println("a(add): 添加数据到队列");
System.out.println("g(get): 从队列取出数据");
System.out.println("h(head): 查看队列头的数据");
c = scan.next().charAt(0);
switch (c){
case 's':
circleArray.showQueue();
break;
case 'e':
scan.close();
flag = false;
break;
case 'a':
int i = scan.nextInt();
try {
circleArray.add(i);
}catch (RuntimeException e){
System.out.println(e.getMessage());
}
break;
case 'g':
try {
circleArray.delete();
}catch (RuntimeException e){
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int i1 = circleArray.headQueue();
System.out.println(i1);
}catch (RuntimeException e){
System.out.println(e.getMessage());
}
break;
}
}
}
}
class CircleArray{
private int[] circleArr;//存放数据的数组
private int front;//首指针
private int rear;//尾指针
private int maxSize;//数组长度
//初始化环形数组
public CircleArray(int maxSize) {
this.maxSize = maxSize;
circleArr = new int[maxSize];
front = 0;
rear = 0;
}
/*
判断数组是否为空
*/
public boolean isEmpty(){
return front == rear;
}
/*
判断数组是否已满
*/
public boolean isFull(){
return (rear + 1) % maxSize == front;
}
/*
添加数据
*/
public void add(int n){
if (isFull()){
throw new RuntimeException("对列已满");
}
circleArr[rear] = n;
rear = (rear + 1) % maxSize;
}
/*
出队列并获取列数据
*/
public int delete(){
if (isEmpty()){
throw new RuntimeException("队列无数据");
}
int value = circleArr[front];
front = (front + 1) % maxSize;
return value;
}
/*
显示队列所有数据
*/
public void showQueue(){
if (isEmpty()){
System.out.println("队列暂无数据");
return;
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d] = %d\n",i % maxSize,circleArr[i % maxSize]);
}
}
/*
显示队列的头数据
*/
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列无数据");
}
return circleArr[front];
}
/*
获取有效数据个数
*/
public int size(){
return (rear + maxSize - front) % maxSize;
}
}