环形队列的java语言描述

最近学习了环形队列,但很多代码都存在一些问题,就自己写了一份。
package queuq;

public class ArrayQueue {

    private final int[] array;

    private int rear;

    private int front;

    private int currentSize;

    private final int maxSize;



    public ArrayQueue(int maxSize) {
        // 由于队列最后一位不使用,所有将其+1,保证最大尺寸与所输入的数字相同
        this.maxSize = maxSize;
        array = new int[this.maxSize + 1];
        System.out.println("array.length=" + array.length);
        rear = 0;
        front = 0;
        currentSize = 0;
    }

    // 判断队列是否已满
    public boolean isFull(){

        return currentSize == maxSize;

    }

    public boolean isEmpty(){

        return currentSize == 0;

    }

    // 添加元素
    public void enqueue(int val){

        if (isFull()){
            System.out.println("队列已满");
            return;
        }

        array[rear] = val;
        rear = (rear + 1) % maxSize;
        currentSize++;
    }

    public int getRear(){
        return rear;
    }

    public int getFront() {
        return front;
    }

    // 出列
    public int dequeue(){

        if (isEmpty()){
            throw new RuntimeException("空");
        }

        currentSize--;
        int res = array[front];
        front = (front + 1) % maxSize;
        return res;
    }

    public int removeLast(){

        if (isEmpty()){
            throw new RuntimeException("空");
        }

        currentSize--;
        rear = this.rear == 0 ? maxSize - 1 : (rear - 1) % maxSize;
        return array[rear];
    }

    // 查看元素
    public void findQueue(){

        if (isEmpty()){
            throw new RuntimeException("空");
        }

        for (int i = front; i < currentSize; i++){
            System.out.printf("array[%d]=%d\n", i, array[i]);
        }
    }

    // 查看对头元素
    public int peek(){
     if (isEmpty()){
            throw new RuntimeException("空");
        }
        return array[front];
    }

    // 显示末尾元素
    public int Rear(){

        if (isEmpty()){
            throw new RuntimeException("空");
        }
        return this.rear == 0 ? array[maxSize - 1] : array[rear - 1];
    }

    public int size(){
        return currentSize;
    }
}  
自己写的代码参考了数据结构java语言描述,增加了一个currentSize这个属性来记录队列的长度。
网上很多代码都是直接用rear和front来判断队列的长度,这样很难理解,而且容易出bug,还是维护一个currentSize比较方便。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值