力扣 641. 设计循环双端队列 数组模拟循环双端队列

70 篇文章 0 订阅
11 篇文章 0 订阅

https://leetcode-cn.com/problems/design-circular-deque/
在这里插入图片描述
思路:因为队列的容量在初始化之后就不会再改变了,所以可以用数组来模拟。 f r o n t 、 r e a r front、rear frontrear分别代表队列的头部和尾部( r e a r rear rear实际上指向的队尾元素的下一个位置),初始时二者相等,为了将队列空与队列满的情况区分开来,我们需要额外花费 1 1 1个元素的空间(这个空间是不放置任何元素的)。通过下标对 s i z e size size取模这一操作即可实现循环位移。

class MyCircularDeque {
public:
    /** Initialize your data structure here. Set the size of the deque to be k. */
    //为了区分队列 空/非空 需要一个元素的额外空间
    MyCircularDeque(int k):arr(new int[k+1]),front(0),rear(0),size(k+1) {
        
    }
    
    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    bool insertFront(int value) {
        if(isFull())
            return 0;
        front=(front-1+size)%size;
        arr[front]=value;
        return 1;
    }
    
    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    bool insertLast(int value) {
        if(isFull())
            return 0;
        arr[rear]=value;
        rear=(rear+1)%size;
        return 1;
    }
    
    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    bool deleteFront() {
        if(isEmpty())
            return 0;
        front=(front+1)%size;
        return 1;
    }
    
    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    bool deleteLast() {
        if(isEmpty())
            return 0;
        rear=(rear-1+size)%size;
        return 1;
    }
    
    /** Get the front item from the deque. */
    int getFront() {
        if(isEmpty())
            return -1;
        return arr[front];
    }
    
    /** Get the last item from the deque. */
    int getRear() {
        if(isEmpty())
            return -1;
        return arr[(rear-1<0)?size-1:rear-1];
    }
    
    /** Checks whether the circular deque is empty or not. */
    bool isEmpty() {
        //二者相等为空
        return rear==front;
    }
    
    /** Checks whether the circular deque is full or not. */
    bool isFull() {
        //尾巴的下一个元素为头部 说明队列已满
        return (rear+1)%size==front;
    }
private:
    int *arr;
    //front指向队列头部 rear指向队列尾部(末尾元素的下一个位置)
    int size,front,rear;
};

/**
 * Your MyCircularDeque object will be instantiated and called as such:
 * MyCircularDeque* obj = new MyCircularDeque(k);
 * bool param_1 = obj->insertFront(value);
 * bool param_2 = obj->insertLast(value);
 * bool param_3 = obj->deleteFront();
 * bool param_4 = obj->deleteLast();
 * int param_5 = obj->getFront();
 * int param_6 = obj->getRear();
 * bool param_7 = obj->isEmpty();
 * bool param_8 = obj->isFull();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值