java循环队列实现代码

复制代码
 1 public class Queue {
 2     //队首指针
 3     private int front;
 4     //队尾指针
 5     private int rear;
 6     //数组
 7     private int[] arr;
 8     //数组最大长度
 9     private int maxSize;
10 
11     //初始化队列长度
12     public Queue(int maxSize){
13         this.maxSize = maxSize;
14         arr = new int[maxSize];
15     }
16 
17     //是否为空
18     public boolean isEmpty(){
19         if (front == rear){
20             return true;
21         }
22         else
23             return false;
24     }
25 
26     //是否为满队列
27     public boolean isFull(){
28         if(front == (rear+1)%maxSize){
29             return true;
30         }
31         else
32             return false;
33     }
34 
35     //计算当前元素个数
36     public int queueSize(){
37         return (rear + maxSize - front) % maxSize;
38     }
39 
40     //进队
41     public void enQueue(int x){
42         //判断是否为满队列
43         if(isFull()){
44             throw new RuntimeException("队列已满,无法插入新元素");
45         }
46         arr[rear] = x;
47         rear = (rear+1)%maxSize;
48     }
49 
50     //出队
51     public int deQueue(){
52         if(isEmpty()){
53             throw new RuntimeException("队列为空,无法出队元素");
54         }
55         int value = arr[front];
56         front = (front + 1)%maxSize;
57         return value;
58     }
59 
60     //显示队列里的数据
61     public void showQueue(){
62         if(isEmpty()){
63             System.out.println("队列为空");
64             return;
65         }
66         for (int i = front; i < front + queueSize() ; i++){
67             System.out.println("arr[" + i + "] = " + arr[i]);
68         }
69         return;
70     }
71 }
复制代码

 

posted @   何侠客  阅读(886)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示