题源: 力扣(LeetCode)https://leetcode-cn.com/problems/design-circular-deque
题目描述:
设计实现双端队列。
你的实现需要支持以下操作:
MyCircularDeque(k):构造函数,双端队列的大小为k。
insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。
insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。
deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。
deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。
getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。
getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。
isEmpty():检查双端队列是否为空。
isFull():检查双端队列是否满了。
思路:循环双端队列,实质上就是循环队列(在队头和队尾都可以进队列和出队列的循环队列),循环队列详情请看我上一篇博客:从零开始算法之路 ---- 设计循环队列
小提示: 1.循环队列最多只能存放 maxSize - 1 个元素
代码:
class MyCircularDeque {
private:
// 定义对头指针、队尾指针、队列最大存储数
int front,rear;
int *elements;
int maxSize;
public:
/** Initialize your data structure here. Set the size of the deque to be k. */
MyCircularDeque(int k) {
// 初始化 对头指针、队尾指针、队列最大存储数
front = 0;
rear = 0;
// 循环队列最多能存储 maxSize - 1 个元素,
// 所以想要存 k 个元素 ,maxSize 得等于 k + 1
maxSize = k + 1;
// 建立一个最多具有 k 个元素的空队列
// 创建队列空间
elements = new int[maxSize];
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
bool insertFront(int value) {
// 判断队列是否满,满则返回
if(isFull() == true) return false;
// 队头进元素,队头指针减 1
front = (front - 1 + maxSize)%maxSize;
// 元素从队头进队列
elements[front] = value;
return true;
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
bool insertLast(int value) {
// 判断队列是否满,满则返回 false
if(isFull() == true) return false;
// 元素从队尾进队列
elements[rear] = value;
// 队尾进元素,队尾指针 加 1
rear = (rear + 1) % maxSize;
return true;
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
bool deleteFront() {
// 判断队列是否空,空则返回 false
if( isEmpty() == true) return false;
// 保存队头元素
int x = elements[front];
// 队头元素出队列,队头指针 进 1
front = (front + 1) % maxSize;
return true;
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
bool deleteLast() {
// 判断队列是否空,空则返回 false
if( isEmpty() == true) return false;
// 队尾元素出队列,队尾指针 减 1
rear = (rear - 1 + maxSize)%maxSize ;
return true;
}
/** Get the front item from the deque. */
int getFront() {
// 判断队列是否空,空则返回 false
if( isEmpty() == true) return -1;
// 返回队头元素
return elements[front];
}
/** Get the last item from the deque. */
int getRear() {
// 判断队列是否空,空则返回 false
if( isEmpty() == true) return -1;
// 返回队尾元素
return elements[(rear - 1 + maxSize)%maxSize];
}
/** Checks whether the circular deque is empty or not. */
bool isEmpty() {
return (rear == front)? true : false;
}
/** Checks whether the circular deque is full or not. */
bool isFull() {
return ((rear + 1)%maxSize == front) ? true : false;
}
};
/**
* Your MyCircularDeque object will be instantiated and called as such:
* MyCircularDeque* obj = new MyCircularDeque(k);
* bool param_1 = obj->insertFront(value);
* bool param_2 = obj->insertLast(value);
* bool param_3 = obj->deleteFront();
* bool param_4 = obj->deleteLast();
* int param_5 = obj->getFront();
* int param_6 = obj->getRear();
* bool param_7 = obj->isEmpty();
* bool param_8 = obj->isFull();
*/