0
点赞
收藏
分享

微信扫一扫

leetcode641 设计循环双端队列

我阿霆哥 2022-01-05 阅读 57

思路

一开始想的很复杂,没注意到是循环…注意count++的位置以及涉及到front移动是需要循环防止溢出+maxsize不是+count…

代码

class MyCircularDeque {
private:
    int* queue;
    int front;
    int rear;
    int count;
    int maxsize;
public:
    MyCircularDeque(int k) {
        queue = new int[k];
        front=0;
        rear=0;
        count=0;
        maxsize=k;
    }
    
    bool insertFront(int value) {
        if(isFull())
            return false;      
        front=(front-1+maxsize)%maxsize;
        queue[front]=value;
        count++;
        return true;

    }
    
    bool insertLast(int value) {
        if(isFull())
            return false;
      
        rear=(front+count)%maxsize;
        queue[rear]=value;
        count++;
        return true;

    }
    
    bool deleteFront() {
        if(isEmpty())
            return false;
        front=(front+1)%maxsize;
        count--;
        return true;
        
    }
    
    bool deleteLast() {
        if(isEmpty())
            return false;
        count--;
        return true;
    }
    
    int getFront() {
        if(isEmpty())
            return -1;
        return queue[front];

    }
    
    int getRear() {
        if(isEmpty())
            return -1;
        rear=(front+count-1)%maxsize;
        return queue[rear];

    }
    
    bool isEmpty() {
        if(count==0)
            return true;
        return false;
    }

    bool isFull() {
        if(count==maxsize)
            return true;
        return false;
    }
};

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

相关推荐

0 条评论