| 对前面的数组模拟队列的优化,充分利用数组. 因此将数组看做是一个环形的。(通过取模的方式来实现即可) |


| import java.util.Scanner; |
| |
| public class CircleArrayQueueDemo { |
| |
| public static void main(String[] args) { |
| |
| System.out.println("测试数组模拟环形队列的案例~~~"); |
| |
| CircleArray queue = new CircleArray(4); |
| char key = ' '; |
| Scanner scanner = new Scanner(System.in); |
| boolean loop = true; |
| |
| while (loop) { |
| 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': |
| queue.showQueue(); |
| break; |
| case 'a': |
| System.out.println("输出一个数"); |
| int value = scanner.nextInt(); |
| queue.addQueue(value); |
| break; |
| case 'g': |
| try { |
| int res = queue.getQueue(); |
| System.out.printf("取出的数据是%d\n", res); |
| } catch (Exception e) { |
| |
| System.out.println(e.getMessage()); |
| } |
| break; |
| case 'h': |
| try { |
| int res = queue.headQueue(); |
| System.out.printf("队列头的数据是%d\n", res); |
| } catch (Exception e) { |
| |
| System.out.println(e.getMessage()); |
| } |
| break; |
| case 'e': |
| scanner.close(); |
| loop = false; |
| break; |
| default: |
| break; |
| } |
| } |
| System.out.println("程序退出~~"); |
| } |
| |
| } |
| |
| class CircleArray { |
| private int maxSize; |
| |
| |
| private int front; |
| |
| |
| private int rear; |
| private int[] arr; |
| |
| public CircleArray(int arrMaxSize) { |
| maxSize = arrMaxSize; |
| arr = new int[maxSize]; |
| } |
| |
| |
| public boolean isFull() { |
| return (rear + 1) % maxSize == front; |
| } |
| |
| |
| public boolean isEmpty() { |
| return rear == front; |
| } |
| |
| |
| public void addQueue(int n) { |
| |
| if (isFull()) { |
| System.out.println("队列满,不能加入数据~"); |
| return; |
| } |
| |
| arr[rear] = n; |
| |
| rear = (rear + 1) % maxSize; |
| } |
| |
| |
| public int getQueue() { |
| |
| if (isEmpty()) { |
| |
| throw new RuntimeException("队列空,不能取数据"); |
| } |
| |
| |
| |
| |
| int value = arr[front]; |
| front = (front + 1) % maxSize; |
| return value; |
| |
| } |
| |
| |
| public void showQueue() { |
| |
| if (isEmpty()) { |
| System.out.println("队列空的,没有数据~~"); |
| return; |
| } |
| |
| |
| for (int i = front; i < front + size() ; i++) { |
| System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]); |
| } |
| } |
| |
| |
| public int size() { |
| |
| |
| |
| return (rear + maxSize - front) % maxSize; |
| } |
| |
| |
| public int headQueue() { |
| |
| if (isEmpty()) { |
| throw new RuntimeException("队列空的,没有数据~~"); |
| } |
| return arr[front]; |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗