不循环的单次队列
package DataStructure;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(3);
boolean loop = true;
while (loop){
Scanner sc = new Scanner(System.in);
System.out.println("请选择操作:");
System.out.println("a : add");
System.out.println("g : get");
System.out.println("s : show");
System.out.println("h : head");
System.out.println("e : exit");
switch (sc.next()){
case "a":
try{
arrayQueue.addQueue(sc.nextInt());
} catch (InputMismatchException e){
System.out.println("请输入int类型");
}
break;
case "g":
try{
System.out.println(arrayQueue.getQueue());
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
case "s":
arrayQueue.showQueue();
break;
case "h":
try {
System.out.println(arrayQueue.headQueue());
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
case "e":
System.out.println("退出");
loop = false;
break;
}
}
}
}
// 编写一个队列类
class ArrayQueue {
private int maxSize ;
private int front ;
private int rear ;
private int[] arr ;
// 队列的构造器
public ArrayQueue(int arrMaxSize){
maxSize = arrMaxSize;
arr = new int[arrMaxSize];
front = -1;
rear = -1;
}
// 判断队列是否为满
public boolean isFull(){
return rear == maxSize - 1;
}
// 判断队列是否为空
public boolean isEmpty(){
return rear == front;
}
// 添加数据到队列
public void addQueue(int n){
// 判断队列是否为满
if (isFull()){
System.out.println("队列为满");
}else{
rear ++;
arr[rear] = n;
}
}
// 获取队列中的数据
public int getQueue(){
// 判断队列是否为空
if (isEmpty()){
throw new RuntimeException("队列为空");
}else{
front ++;
return arr[front];
}
}
// 显示队列
public void showQueue(){
// 判断是否为空
if (isEmpty()){
System.out.println("队列为空");
}else{
for (int i = front+1 ; i <= rear ; i ++){
System.out.printf("arr[%d]=%d", i , arr[i]);
System.out.println();
}
}
}
// 显示队列的头部数据
public int headQueue(){
// 判断是否为空
if (isEmpty()){
throw new RuntimeException("队列为空");
}else{
return arr[front+1];
}
}
}