日野弥生:勉強しよう

LeetCode 622 - 设计循环队列

发表于2025年02月10日

#设计 #队列 #数组 #链表

设计循环队列的关键在于入队和出队的业务代码。注意检查边界。

class MyCircularQueue {
private:
    /* 至少需要头尾两个索引 */
    int head = -1;
    int tail = -1;

    /* 容器和容量,由于容量是自定义,所以不能使用vector<int>的容量 */
    int size = 0;
    vector<int> data;
public:
    MyCircularQueue(int k) {
        data.resize(k);
        size = k;
    }
    
    bool enQueue(int value) {
        /* 满则无法入队 */
        if(isFull())
            return false;

        /* 空队列入队需要置位head */
        if (isEmpty())
            head = 0;

        /* 循环队列的关键操作 */
        tail = (tail + 1) % size;

        data[tail] = value;
        return true;
    }
    
    bool deQueue() {
        /* 空队列无法出队 */
        if (isEmpty())
            return false;
        
        /* 头尾相等时,彻底出完,置位回初始值 */
        if (head == tail)
        {
            head = -1;
            tail = -1;
            return true;
        }

        /* 循环队列的关键操作 */
        head = (head + 1) % size;
        return true;
    }
    
    int Front() {
        if(isEmpty())
            return -1;
        return data[head];
    }
    
    int Rear() {
        if(isEmpty())
            return -1;
        return data[tail];
    }
    
    bool isEmpty() {
        return head == -1;
    }
    
    bool isFull() {
        /* tail在head前一位时,说明满了 */
        return ((tail + 1) % size) == head;
    }
};

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/design-circular-queue/

上一篇

LeetCode 933 - 最近的请求次数

下一篇

LeetCode 346 - 数据流中的移动平均值