700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java版数据结构之数组模拟环形队列demo

Java版数据结构之数组模拟环形队列demo

时间:2022-03-08 14:16:16

相关推荐

Java版数据结构之数组模拟环形队列demo

Java版数据结构之数组模拟环形队列demo

我的代码仓库:/zhuangbinan/datastructure

类 CircleArray

package club.zhuangbinan.queue;/*** 数组模拟环形队列demo*/public class CircleArray {private int[] arr;private int maxSize;// front 和 rear 在环形数组中初始值为0private int front;private int rear;public CircleArray(int maxSize) {this.maxSize = maxSize;this.arr = new int[maxSize];this.front = 0;this.rear = 0;}private boolean isFull() {return (rear + 1) % maxSize == front;}private boolean isEmpty() {return rear == front;}public int size() {return (rear - front + maxSize) % maxSize;}public void add(int n) {if (isFull()) {System.out.println("环形数组已满,无法加入");return;}this.arr[rear] = n;rear = (rear + 1) % maxSize;}/*** 拿出一个* @return 队列的第一个*/public int get(){if (isEmpty()) {throw new RuntimeException("数组模拟的环形队列已经是空的,无法再取");}int result = this.arr[front];front = (front + 1) % maxSize;return result;}public int queryHead(){if (isEmpty()) {throw new RuntimeException("数组模拟的环形队列是空的");}return arr[front];}public void showCircleQueue(){if (isEmpty()) {System.out.println("当前环形队列为空");}for (int i = front; i < front + size(); i++) {System.out.printf("arr[%d]=%d\n",i % maxSize , arr[i % maxSize]);}}}

类 CirCleArrayWithScannerDemo , main方法所在

package club.zhuangbinan.queue;import java.util.Scanner;public class CirCleArrayWithScannerDemo {public static void main(String[] args) {CircleArray que = new CircleArray(4);Scanner scanner = new Scanner(System.in);boolean loop = false;char key;while (!loop) {try {System.out.println("请按如下提示输入:");System.out.println("s(show): 显示队列");System.out.println("e(exit): 退出程序");System.out.println("a(add): 添加数据到队列");System.out.println("g(get): 从队列取出数据");System.out.println("h(head): 查看队列头的数据");key = scanner.next().charAt(0);//接收一个字符switch (key) {case 's':que.showCircleQueue();break;case 'e':System.out.println("退出程序");loop = true;break;case 'a':System.out.println("请再输入一个数字:");que.add(scanner.nextInt());System.out.println("输入的数字被添加到队列中");break;case 'g':System.out.println("取出的数字为:" + que.get());break;case 'h':System.out.println("队列头数据:" + que.queryHead());break;default:System.out.println("您的输入有误,请重新输入!");}} catch (Exception e) {e.printStackTrace();}}scanner.close();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。