Queue类:
public class Queue {
private int[] arr;
private int front;
private int rear;
private int maxSize;
public Queue(int maxSize){
arr = new int[maxSize];
this.maxSize = maxSize;
front = rear = -1;
}
/**
* 判断队列是否为空
* @return
*/
private boolean isEmpty(){
return front == rear;
}
/**
* 判断队列是否已满
* @return
*/
private boolean isFull(){
return rear == maxSize - 1;
}
/**
* 添加数据
* @param value
*/
public void add(int value){
//队列已满
if (isFull()){
throw new RuntimeException("队列已满,数据添加失败!");
}
rear++;
arr[rear] = value;
System.out.println("数据添加成功");
}
/**
* 弹出队首元素
* @return
*/
public int get(){
if (isEmpty()){
throw new RuntimeException("队列为空,无法弹出数据!");
}
front++;
return arr[front];
}
/**
* 展示队列元素
*/
public void showQueue(){
int i = 0;
for (int value : arr){
System.out.printf("a[%d] = %d\n",i,value);
i++;
}
}
/**
* 展示队首元素
* @return
*/
public int headData(){
if (isEmpty()){
throw new RuntimeException("队列为空,无法展示队首元素");
}
return arr[front + 1];
}
}
主函数(测试):
import java.util.Scanner;
public class QueueBaseArrayTest {
public static void main(String[] args) {
boolean loop = true;
Scanner scan = new Scanner(System.in);
System.out.println("Enter maxSize of Queue:");
int maxSize = Integer.parseInt(scan.next());
Queue queue = new Queue(maxSize);
while (loop){
System.out.println("----------------------------------------------------------------------------------");
System.out.println("Enter 's' to show Queue");
System.out.println("Enter 'a' to add data for Queue");
System.out.println("Enter 'g' to get data from Queue");
System.out.println("Enter 'h' to get data of headIndex from Queue");
System.out.println("Enter 'e' to exit the program");
String str = scan.next().toLowerCase();
switch (str){
case "s" -> queue.showQueue();
case "a" -> {
System.out.println("Please enter IntData of Queue:");
int value = scan.nextInt();
try {
queue.add(value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
case "g" -> {
try {
System.out.println("Return the data [" + queue.get() + "]");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
case "h" -> {
try {
System.out.println("The head data is [" + queue.headData() + "]");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
case "e" -> loop = false;
}
}
System.out.println("Program exit");
}
}