java实现循环队列

本文介绍了如何使用Java实现循环队列,包括实现思路和简单的测试案例,帮助读者理解循环队列的工作原理。
摘要由CSDN通过智能技术生成

实现思路:

实现的代码:

 

public class CircleQuenue {
    private int maxSize;// 最大长度
    private int[] arr; // 数组,存放值
    private int font;// 队列头
    private int rear;// 队列尾

    public CircleQuenue(int arrMaxSize){
        maxSize = arrMaxSize;
        arr = new int[maxSize];
    }

    // 判断是否为空
    public boolean isEmpty(){
        return rear == font;
    }

    // 判断是否为满
    public boolean isFull(){
        return (rear + 1) % maxSize == font;
    }

    // 取出一个数据
    public int getQuenue(){
        if(isEmpty()){
            throw new RuntimeException("为空。。");
        }
        int value = arr[font];
        font = (font + 1) % maxSize;
        return value;
    }

    // 添加一个数据
    public void addQuenue(int n){
        if(isFull()){
            throw new RuntimeException("队列已满。。");
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    // 显示数据
    public void showQuenue(){
        if(isEmpty()){
            throw new RuntimeException("队列为空。。");
        }
        for (int i = font; i < font + size() ; i++) {
            System.out.printf("arr[%d]=%d\n",i % maxSize,arr[i%maxSize]);
        }
    }

    // 得到队列的有效个数
    public int size(){
        return (rear + maxSize - font)%maxSize;
    }

    // 得到头指针
    public int headQuenue(){
        if(isEmpty()){
            throw new RuntimeException("队列为空。。");
        }
        return arr[font];
    }
}

简单的测试:

 public static void main(String[] args) {
        CircleQuenue quenue = new CircleQuenue(4);
        System.out.println(quenue.isEmpty());
        quenue.addQuenue(12);
        quenue.showQuenue();
        System.out.println(quenue.headQuenue());
        System.out.println(quenue.getQuenue());

        quenue.addQuenue(34);
        quenue.addQuenue(23);
        quenue.addQuenue(22);
        quenue.showQuenue();

        System.out.println(quenue.getQuenue());;
        quenue.addQuenue(122);
        quenue.showQuenue();
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值