Leetcode——622. 设计循环队列

|▌冷眼眸甩不掉的悲伤 提交于 2020-02-14 18:00:06

在这里插入图片描述
这里用变量qsize来指示队列中含有多少个元素,判断队列满或空。在编码的时候要注意数组下标的边界就好了。

注意一点:自己因为很长时间不写c++对c++的语法不是很熟了,新建一个动态int数组为new int[length_of_the_array] 而 new int(int_value)是new一个int数,值为int_value,让我找了好长时间才发现这个错误555.

class MyCircularQueue 
{
public:
    int head;
    int rear;
    int num;
    int qsize;
    int* qu;
    /** Initialize your data structure here. Set the size of the queue to be k. */
    MyCircularQueue(int k)
    {
        head=0;
        rear=0;
        qsize=0;
        num=k;
        qu=new int[k];
    }

    /** Insert an element into the circular queue. Return true if the operation is successful. */
    bool enQueue(int value)
    {
        if(qsize==num)
        {
            return false;
        }
        else
        {
            qu[rear]=value;
            rear=(rear+1)%num;
            qsize++;
            return true;
        }
    }

    /** Delete an element from the circular queue. Return true if the operation is successful. */
    bool deQueue()
    {
        if(qsize==0)
        {
            return false;
        }
        else
        {
            head=(head+1)%num;
            qsize--;
            return true;
        }
    }

    /** Get the front item from the queue. */
    int Front()
    {
        if(qsize==0)
        {
            return -1;
        }
        else
        {
            return qu[head];
        }
    }

    /** Get the last item from the queue. */
    int Rear()
    {
        if(qsize==0)
        {
            return -1;
        }
        else
        {
            int loc=rear-1;
            if(loc<0)
                loc=num-1;
            return qu[loc];
        }
    }

    /** Checks whether the circular queue is empty or not. */
    bool isEmpty()
    {
        if(qsize>0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    /** Checks whether the circular queue is full or not. */
    bool isFull()
    {
        if(qsize==num)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

/**
 * 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();
 */
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!