编辑代码


package queue;

import java.util.Scanner;

public class ArrayCircleQueue {

private int maxSize; // 队列的实际容量大小

private int front; // 第1个元素所在位置的前1个位置的索引

private int rear; // 最后1个元素所在位置的索引

private int[] queue; // 队列本身


public ArrayCircleQueue(int logicSize){

maxSize = logicSize + 1;

queue = new int[maxSize];

}


public boolean isFull(){

return (rear + 1) % maxSize == front;

}


public boolean isEmpty(){

return front == rear;

}


public int size(){

return (rear - front + maxSize) % maxSize;

}


public boolean push(int n){

// 入队前先检查是否已满

if(isFull()){

System.out.println("队满!");

return false;

}

rear = (rear + 1) % maxSize;

queue[rear] = n;

return true;

}

public int pop(){

// 出队前先检查是否为空,如果为空抛出异常

if (isEmpty()){

throw new RuntimeException("队空!");

}

front = (front + 1) % maxSize;

return queue[front];

}


public int front(){

// 判断是否队空

if (isEmpty()){

throw new RuntimeException("队空!");

}

return queue[(front + 1) % maxSize];

}


public void showQueue(){

if(isEmpty()){

System.out.println("[]");

return;

}

for (int i = (front+1) % maxSize; i <= front+size(); i++) {

System.out.printf("queue[%d]=%d\n",i % maxSize,queue[i % maxSize]);

}

}


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("请输入生成队列的大小:");

int n = sc.nextInt();

// 去除多余的换行符

sc.nextLine();

ArrayCircleQueue arrayQueue = new ArrayCircleQueue(n);

// 菜单

loop:

while (true) {

System.out.println("1、查看队列元素个数");

System.out.println("2、入队");

System.out.println("3、出队");

System.out.println("4、拿队首元素");

System.out.println("5、打印队列");

System.out.println("6、退出");

System.out.print("请选择:");

String choice = sc.nextLine();

switch (choice){

case "1":

int size = arrayQueue.size();

System.out.println("size="+size);

break;

case "2":

System.out.print("入队元素:");

int el = sc.nextInt();

// 去除多余的换行符

sc.nextLine();

arrayQueue.push(el);

break;

case "3":

try {

int pop = arrayQueue.pop();

System.out.println("出队元素:"+pop);

} catch (Exception e) {

System.out.println(e.getMessage());

}

break;

case "4":

try {

int front = arrayQueue.front();

System.out.println("队首元素"+front);

} catch (Exception e) {

System.out.println(e.getMessage());

}

break;

case "5":

arrayQueue.showQueue();

break;

default:

break loop;

}

}

}

}