Java数据结构与算法之循环队列

package com.lee.queue;

public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        CircleArrayQueue circleQueue = new CircleArrayQueue(5);
        circleQueue.addQueue(10);
        circleQueue.addQueue(20);
        circleQueue.addQueue(30);
        circleQueue.addQueue(40);
        circleQueue.showQueue();
        System.out.println("出队" + circleQueue.getQueue());
        circleQueue.showQueue();
        System.out.println("添加元素50");
        circleQueue.addQueue(50);
        circleQueue.showQueue();
        System.out.println("出队" + circleQueue.getQueue());
        circleQueue.showQueue();
        System.out.println("添加元素60");
        circleQueue.addQueue(60);
        circleQueue.showQueue();
        System.out.println("出队" + circleQueue.getQueue());
        circleQueue.showQueue();
        System.out.println("添加元素60");
        circleQueue.addQueue(70);
        circleQueue.showQueue();
    }
}

class CircleArrayQueue{
    private int maxSize;        //队列容量
    private int rear;           //队列尾部标示,指向队列的最后一个元素的下一个位置
    private int front;          //队列头部标示,指向队列的第一个元素
    private int[] arr;          //存放元素的数组

    public CircleArrayQueue(int maxSize){
        this.maxSize = maxSize;
        front = 0;
        rear = 0;
        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("队列满,无法入队");
        }
        arr[rear] = n;                          //数据入队
        rear = (rear + 1) % maxSize;            //rear后移,取模
    }

    //出队
    public int getQueue(){
        if(isEmpty()){
            throw new RuntimeException("队列空,无法出队");
        }
        int data = arr[front];
        front = (front + 1) % maxSize;
        return data;
    }

    //队列有效元素个数
    public int size(){
        return (rear + maxSize - front) % maxSize;
    }

    //输出队列
    public void showQueue(){
        if(isEmpty()){
            System.out.println("队列空,没有数据");
        }
        for(int i = front; i < front + size(); i++){
            System.out.println("arr[" + (i % maxSize) + "]=" + arr[i % maxSize]);
        }
    }

    //显示头元素
    public int headQueue(){
        if(isEmpty()){
            throw new RuntimeException("队列空,没有头元素");
        }
        return arr[front];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeJR

如果觉得有用请赏一个呗!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值