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];
    }
}
发布了63 篇原创文章 · 获赞 28 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41286145/article/details/103755959