package com.queue;
import java.util.Scanner;
import javax.management.JMRuntimeException;
public class CircleArrayQueue {
public static void main(String[] args) {
//测试
CircleArrayQueue Queue = new CircleArrayQueue();
circleArrayQueue queue = Queue.new circleArrayQueue();
queue.createCircleQueue(4);
Scanner scanner = new Scanner(System.in);
char key = ' ';//用户选择
boolean loop = true;
while (loop) {
System.out.println("*****************************");
System.out.println("s:显示队列所有元素");
System.out.println("a:添加元素");
System.out.println("g:取出元素");
System.out.println("h:显示队头元素");
System.out.println("e:退出程序");
System.out.println("*****************************");
System.out.println("请输入你的选择");
key = scanner.next().charAt(0);
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("请输入要添加的数据");
int data = scanner.nextInt();
queue.addQueue(data);;
break;
case 'g':
try {
queue.getQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
queue.getHead();;
break;
case 'e':
loop = false;
scanner.close();
break;
default:
break;
}
}
}
//使用数组模拟循环队列
class circleArrayQueue{
private int maxSize;//队列最大长度
private int front;//指向队头
private int rear;//指向队尾下一个元素
private int arr[];//用来模拟循环队列的数组
//创造队列
public void createCircleQueue(int arrMaxSize) {
maxSize = arrMaxSize;
front = rear = 0;
arr = new int[maxSize];
}
//判断队列是否为空
public boolean isEmpty() {
return rear == front;
}
//判断队列是否已满
public boolean isFull() {
return (rear+1) % maxSize == front;
}
//往队列中添加元素
public void addQueue(int data) {
//判断队列是否已满
if (isFull()) {
System.out.println("队列已满,不能添加元素");
return;
}
arr[rear] = data;
rear = (rear + 1) % maxSize;
}
//队头元素出队列
private void getQueue() {
//判断是否为空
if (isEmpty()) {
//抛出异常
throw new RuntimeException("队列为空");
}
System.out.println(arr[front]);
front = (front + 1) % maxSize;
}
//遍历队列
private void showQueue() {
for (int i = front; i < front + size(); i++) {
System.out.print(arr[i % maxSize] + "\t");
}
System.out.println();
}
//得到队头元素
public void getHead() {
System.out.println(arr[front]);
}
//计算队列中元素个数
public int size() {
return (rear + maxSize - front) % maxSize;
}
}
}
数组模拟循环队列
最新推荐文章于 2023-09-04 21:48:31 发布