622. Design Circular Queue

https://leetcode.com/problems/design-circular-queue/

实现大小为k的循环队列。初始化大小为k的数组,两个指针start和end,分别代表队列的首和尾所在位置。enqueue时end后移,end = (end + 1) % k;同理dequeue时start后移。start和end初始化为0和-1。

/*
 * @lc app=leetcode id=622 lang=cpp
 *
 * [622] Design Circular Queue
 */

// @lc code=start
class MyCircularQueue {
public:
    vector<int> q;
    int start, end, size;
    /** Initialize your data structure here. Set the size of the queue to be k. */
    MyCircularQueue(int k) {
        q.resize(k);
        start = 0;
        end = -1;
        size = 0;
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    bool enQueue(int value) {
        if (size == q.size()) return false;
        end = (end + 1) % q.size();
        q[end] = value;
        ++size;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    bool deQueue() {
        if (isEmpty()) return false;
        start = (start + 1) % q.size();
        --size;
        return true;
    }
    
    /** Get the front item from the queue. */
    int Front() {
        return isEmpty() ? -1 : q[start];
    }
    
    /** Get the last item from the queue. */
    int Rear() {
        return isEmpty() ? -1 : q[end];
    }
    
    /** Checks whether the circular queue is empty or not. */
    bool isEmpty() {
        return size == 0;
    }
    
    /** Checks whether the circular queue is full or not. */
    bool isFull() {
        return size == q.size();
    }
};

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue* obj = new MyCircularQueue(k);
 * bool param_1 = obj->enQueue(value);
 * bool param_2 = obj->deQueue();
 * int param_3 = obj->Front();
 * int param_4 = obj->Rear();
 * bool param_5 = obj->isEmpty();
 * bool param_6 = obj->isFull();
 */
// @lc code=end

Last updated