【Leetcode】641.设计循环双端队列C++

在这里插入图片描述
在这里插入图片描述

class MyCircularDeque
{
public:
    int My_k;
    int front;
    int rear;
    int *My_queue;
    /** Initialize your data structure here. Set the size of the deque to be k. */
    MyCircularDeque(int k)
    {
        My_k = k;
        front = k * 10;
        rear = k * 10;
        My_queue = new int[k];
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    bool insertFront(int value)
    {
        if (isFull())
        {
            return false;
        }
        else
        {
            front--;
            My_queue[front % My_k] = value;
            return true;
        }
    }

    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    bool insertLast(int value)
    {
        if (isFull())
        {
            return false;
        }
        else
        {
            My_queue[rear % My_k] = value;
            rear++;
            return true;
        }
    }

    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    bool deleteFront()
    {
        if (isEmpty())
        {
            return false;
        }
        else
        {
            front++;
            return true;
        }
    }

    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    bool deleteLast()
    {
        if (isEmpty())
        {
            return false;
        }
        else
        {
            rear--;
            return true;
        }
    }

    /** Get the front item from the deque. */
    int getFront()
    {
        if (isEmpty())
        {
            return -1;
        }
        else
        {
            return My_queue[front % My_k];
        }
    }

    /** Get the last item from the deque. */
    int getRear()
    {
        if (isEmpty())
        {
            return -1;
        }
        else
        {
            return My_queue[(rear + My_k - 1) % My_k];
        }
    }

    /** Checks whether the circular deque is empty or not. */
    bool isEmpty()
    {
        if (rear - front)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    /** Checks whether the circular deque is full or not. */
    bool isFull()
    {
        if (rear - front < My_k)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
};
发布了103 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104105018