import java.util.Scanner;
/**
* @className CircleArrayQueueDemo
* @author JopenChen
* @date 2020-09-08 12:48
* @description 循环数组队列
*/
public class CircleArrayQueueDemo {
public static void main(String[] args) {
CircleArrayQueue circleArrayQueue = new CircleArrayQueue(4);
boolean loop = true;
Scanner scanner = new Scanner(System.in);
while (loop) {
System.out.println("a(add),添加元素");
System.out.println("p(peek),获取头元素");
System.out.println("g(get),取出元素");
System.out.println("s(show),打印所有元素");
System.out.println("e(exit),退出程序");
char operation = scanner.next().charAt(0);
switch (operation) {
case 'a' :
System.out.println("请输入一个值:");
int value = scanner.nextInt();
try {
circleArrayQueue.add(value);
} catch (RuntimeException e) {
e.printStackTrace();
}
break;
case 'p' :
try {
circleArrayQueue.peek();
} catch (RuntimeException e) {
e.printStackTrace();
}
break;
case 'g' :
try {
circleArrayQueue.get();
} catch (RuntimeException e) {
e.printStackTrace();
}
break;
case 's' :
try {
circleArrayQueue.show();
} catch (RuntimeException e) {
e.printStackTrace();
}
break;
case 'e' :
loop = false;
System.out.println("程序退出");
break;
default:
break;
}
}
}
}
class CircleArrayQueue{
/**队列头*/
private int front;
/**队列尾*/
private int rear;
/**队列最大容量*/
private int maxSize;
/**实现队列的数组*/
private int[] array;
/**
* 初始化队列
*/
public CircleArrayQueue(int maxSize){
this.maxSize = maxSize;
array = new int[this.maxSize];
}
/**
* 判断是否为空
*/
public boolean isEmpty() {
return front == rear;
}
/**
* 判断是否为满
*/
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
/**
* 查看队列
*/
public void show() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = front; i < front + elementSum(); i++) {
System.out.printf("array[%d] = %d\n", i % maxSize, array[i % maxSize]) ;
}
}
/**
* 有效元素数
*/
public int elementSum() {
return (rear + maxSize - front) % maxSize;
}
/**
* 添加元素
*/
public void add(int element) {
if (isFull()) {
throw new RuntimeException("队列·为满,不可插入");
}
array[rear] = element;
rear = (rear + 1) % maxSize;
}
/**
* 取出元素
*/
public int get() {
if (isEmpty()) {
throw new RuntimeException("队列为空,不可取出");
}
int temp = array[front];
front = (front + 1) % maxSize;
return temp;
}
/**
* 取出头元素
*/
public int peek() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法读取头元素");
}
System.out.printf("array[%d] = %d", front, array[front]);
return array[front];
}
}
数组模拟循环队列
最新推荐文章于 2023-09-04 21:48:31 发布