设计循环队列

描述:

设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。

循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。

思路: 

认为循环队列尾部为空
(1)先写循环队列类的属性,底层实现的数组elem,指向头的指针front,指向尾的指针rear
在写类的构造器,队列的长度有几个元素,数组尾部为空,所以数组长度为队列长度+1
(2)判断队列为空,若front==rear,则为空
(3)判断队列满,若rear的下一个下标是front,此时队列满
(4)入队,若队列满返回false,此时rear指向可以存放的元素,this.elem[this.rear]= val,rear后移一位,因为是环,所以还是这样 this.rear = (this.rear +1) % this.elem.length,最后返回true
(5)出队,若队列空返回false,此时front指向可以出队的元素,让front直接后移即可,
this.front = (this.front + 1) % this.elem.length,最后返回true
(6)得到队首,若队列为空返回-1,直接return front下标指向的元素
(7)得到队尾,若队列为空返回-1,分两种情况,若rear指向0,队尾在最后,返回数组长度-1指向的元素,若rear!=0,返回rear-1指向的元素即可

class MyCircularQueue {
    public int[] elem;
    public int front;
    public int rear;

    public MyCircularQueue(int k) {
        this.elem = new int[k + 1];
    }
    
    public boolean enQueue(int value) {
        if(isFull()){
            return false;
        }
        this.elem[this.rear] = value;
        this.rear = (this.rear + 1) % this.elem.length;
        return true;
    }
    
    public boolean deQueue() {
        if(isEmpty()){
            return false;
        }
        this.front = (this.front + 1) % this.elem.length;
        return true;
    }
    
    public int Front() {
        if(isEmpty()){
            return -1;
        }
        return this.elem[this.front];
    }
    
    public int Rear() {
        if(isEmpty()){
            return -1;
        }
        return this.rear == 0 ? this.elem[this.elem.length - 1] : this.elem[this.rear - 1];
    }
    
    public boolean isEmpty() {
        return this.front == this.rear;
    }
    
    public boolean isFull() {
       return  (this.rear + 1) % this.elem.length == this.front ?  true :  false;

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

DU777DU

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值