欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-04 08:31:14
...

https://leetcode-cn.com/problems/design-circular-deque/
力扣 641. 设计循环双端队列 数组模拟循环双端队列
思路:因为队列的容量在初始化之后就不会再改变了,所以可以用数组来模拟。frontrearfront、rear分别代表队列的头部和尾部(rearrear实际上指向的队尾元素的下一个位置),初始时二者相等,为了将队列空与队列满的情况区分开来,我们需要额外花费11个元素的空间(这个空间是不放置任何元素的)。通过下标对sizesize取模这一操作即可实现循环位移。

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();
 */