1、基本介绍
2、应用实例(数组模拟环形队列)
package queue;import java.util.Scanner;public class ArrayRingQueue {public static void main(String[] args) {RingQueue queue = new RingQueue(3);Scanner scanner = new Scanner(System.in);boolean loop = true;char op;while(loop) {System.out.println("\n添加数据到环形队列(i)");System.out.println("删除环形队列的数据(r)");System.out.println("打印环形队列的数据(p)");System.out.println("查看环形队列首元素(g)");System.out.println("查看环形队列元素个数(c)");System.out.println("查看环形队列是否空(e)");System.out.println("查看环形队列是否满(f)");System.out.println("退出程序(q)~");System.out.print("请选择你要执行的操作:");op = scanner.next().charAt(0);switch (op) {case 'i':System.out.print("请输入要入队的元素:");int val = scanner.nextInt();queue.insert(val);break;case 'r':queue.remove();break;case 'p':queue.print();break;case 'g':queue.getFirst();break;case 'c':queue.getCount();break;case 'e':queue.isEmpty();break;case 'f':queue.isFull();break;default:scanner.close();loop = false;break;}}}
}// 数组模拟队列
class RingQueue {private int front; // 指向第一个元素private int rear; // 指向最后一个元素的下一个位置private int maxSize;private int[] arr;public RingQueue(int maxSize) {front = 0;rear = 0;this.maxSize = maxSize;arr = new int[maxSize];}public void insert(int val) {if (isFull()) {throw new RuntimeException("环形队列满啦!");}arr[rear] = val;rear = (rear + 1) % maxSize;System.out.println("元素入队成功~");System.out.printf("入队元素:%d\n", val);}public void remove() {if (isEmpty()) {throw new RuntimeException("环形队列空荡荡~!");}System.out.println("元素出队成功~");System.out.printf("出队元素:%d\n", arr[front]);front = (front + 1) % maxSize;}public void print() {int size = getCount(); // 环形队列元素个数System.out.print("环形队列元素:");for (int i = front; i < rear + size - 1; i++) {System.out.print(arr[i] + " ");}System.out.println();}public void getFirst() {if (isEmpty()) {System.out.println("环形队列为空,请稍后重试!");}System.out.println("环形队首元素:" + arr[front]);}public int getCount() {int count = (rear + maxSize - front) % maxSize;System.out.printf("环形队列元素个数:%d\n", count);return count;}public boolean isEmpty() {if (front == rear) {System.out.println("环形队列为空~");return true;}System.out.println("环形队列有东西~");return false;}public boolean isFull() {if ((rear + 1) % maxSize == front) {System.out.println("环形队列已满~");return true;}System.out.println("还能再装一点~");return false;}}