循环队列--CircularQueue

class MyCircularQueue {
    vector<int> data;
    int head, tail;
    int size;
    
public:
    /** Initialize your data structure here. Set the size of the queue to be k. */
    MyCircularQueue(int k) {
        data.resize(k); //通过resize重新分配资源空间
        head = -1; 
        tail = -1;
        size = k;
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    bool enQueue(int value) {
        if(isFull())
            return false;
        if(isEmpty())
            head = 0; //首次入队,更新队列首位,离开初始化状态
        
        //通过取余可以确定在队列中的任何位置
        tail = (tail + 1) % size;
        data[tail] = value;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    bool deQueue() {
        if(isEmpty())
            return false;
        //出队列后,队列为空,初始化队列首尾到默认值
        if(head == tail) {
            head = tail = -1;
            return true;
        }
        head = (head + 1) % size;
        return true; 
    }
    
    /** Get the front item from the queue. */
    int Front() {
        if(isEmpty())
            return  -1;
        return data[head];
    }
    
    /** Get the last item from the queue. */
    int Rear() {
        if(isEmpty())
            return  -1;
        return data[tail];
    }
    
    /** Checks whether the circular queue is empty or not. */
    bool isEmpty() {
        //认为初始化状态为空,为空后也会重置为初始化状态
        return head == -1; 
    }
    
    /** Checks whether the circular queue is full or not. */
    bool isFull() {
        return (tail + 1) % size == head;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。