【Java】实现一个循环队列

一、题目要求
在这里插入图片描述
二、题目分析
循环队列为了克服假溢出的现象,当尾部添加元素的同时,头部删除元素,当添加的元素到达了最末端,此时造成了“队列已满”的现象,但实际上因为头部的删除,还留有大量空间。
为了解决这一问题,可以采用循环队列。
也就是用rear指向尾部,front指向头部。把队列从逻辑上看成一个环,如下图所示:
在这里插入图片描述
三、代码



class MyCircularQueue {

    private  int front;;
    private  int rear;
    private  int[] elem;

    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        this.elem=new int[k+1];
        this.front=0;
        this.rear=0;
    }

    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if(isFull()){
            return false;
        }
        this.elem[this.rear]=value;
        this.rear=(this.rear+1)%this.elem.length;
        return true;
    }

    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if(isEmpty()){
            return false;
        }
        this.front=(this.front+1)%this.elem.length;
        return true;
    }

    /** Get the front item from the queue. */
    public int Front() {
       if(isEmpty()){
           return -1;
       }else{
           return this.elem[this.front];
       }
    }

    /** Get the last item from the queue. */
    public int Rear() {
       if(isEmpty()){
           return -1;
       }else{
           int index=(this.rear==0)?this.elem.length-1:this.rear-1;
           return this.elem[index];
       }
    }

    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
       if(this.front==this.rear){
           return true;
       }
       return false;
    }

    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
       if((this.rear+1)%this.elem.length==this.front){
           return true;
       }
       return false;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值