美文网首页
循环队列--CircularQueue

循环队列--CircularQueue

作者: krislyy_ | 来源:发表于2018-12-07 14:44 被阅读0次
    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:循环队列--CircularQueue

          本文链接:https://www.haomeiwen.com/subject/xlpthqtx.html