1队列实现的改善,将rear指向数组的尾部空的位置
import java.util.Scanner;
public class ArrayQueue2 {
public static void main(String[] args) {
Queue queue = new Queue(5);
Scanner scanner = new Scanner(System.in);
boolean flag = true;
while (flag) {
System.out.println("a(add)添加元素");
System.out.println("g(get)取元素");
System.out.println("h(head)查看头部元素");
System.out.println("s(show)查看当前队列元素");
System.out.println("e(exit)退出程序");
System.out.println("请输入你的命令:");
String key = scanner.next();
switch (key) {
case "a": {
System.out.println("请输入要添加的元素:");
int n = scanner.nextInt();
queue.addArray(n);
break;
}
case "g": {
try {
int value = queue.getArray();
System.out.println("取出的元素是:" + value);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case "h": {
try {
queue.getHead();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case "s": {
try {
queue.show();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case "e": {
scanner.close();
flag = false;
// System.exit(0);
break;
}
}
}
}
}
// 队列类
class Queue {
private int maxSize;
private int front;
private int rear;
private int[] array;
// 构造器
public Queue(int max) {
maxSize = max;
front = 0;
rear = 0;
array = new int[maxSize];
}
// 判断是否为满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
// 判断是否为空
public boolean isEmpty() {
return rear == front;
}
// 添加元素
public void addArray(int n) {
if (isFull()) {
System.out.println("队列已满!");
return;
}
array[rear] = n; // 添加元素,rear为尾部的后一位元素位置
rear = (rear + 1) % maxSize;
System.out.println("添加成功!");
}
// 取元素
public int getArray() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法进行取元素");
}
int value = array[front];
array[front] = 0;
front = (front + 1) % maxSize;
return value;
}
// 头部元素
public void getHead() {
if (isEmpty()) {
throw new RuntimeException("队列为空,头部元素无法获取");
}
System.out.println("头部元素为:" + array[front]);
}
// 计算长度
public int sumLength() {
return (rear + maxSize - front) % maxSize;
}
// 展示当前队列情况
public void show() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
// 输出有效数据个数
for (int i = front; i < front + sumLength(); i++) {
System.out.printf("array[%d] = %d\n", i%maxSize, array[i%maxSize]);
}
}
}
Java实现的数组队列操作,
该代码示例展示了如何使用Java实现一个基于数组的队列,包括添加元素(add),获取元素(get),查看头部元素(head)以及显示当前队列状态(show)等功能。队列在满时会阻止添加元素,空时不能获取元素。
340

被折叠的 条评论
为什么被折叠?



