题目
解题
1.front指向队列头部第一个有效数字的位置。
rear指向队列尾部最后一个有效数据的下一个位置。
2.判断队列为空isempty():front==rear‘’
判断队列为满isfull():为避免判断为空与满条件相同,空出一个位置,即满的时候有两种情况
(1)front=0,rear=k;
(2)front=i(0<i<k-1),rear=front-1(注意rear是最后一个数据的下一个位置)
所以判断条件为(rear+1)%capacity= =front;
3.insertfront头插:先判断队列是否为满,满的话无法添加数据,返回false,否则就front指向的位置放置数据,front指向下一个位置。
4.尾部删除与添加:
(1)删除:rear指向上一个数据
(2)添加:rear指向位置放置元素,rear指向该数据的下一位
vector<int> arr;
int front;
int rear;
int capacity;
public:
/** Initialize your data structure here. Set the size of the deque to be k. */
MyCircularDeque(int k) {
capacity=k+1;
arr.assign(capacity,0);
front =0;
rear=0;
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
bool insertFront(int value) {
if(isFull())
return false;
front=(front-1+capacity)%capacity;
arr[front]=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;
arr[rear]=value;
rear=(rear+1)%capacity;
return true;
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
bool deleteFront() {
if(isEmpty())
return false;
front=(front+1)%capacity;
return true;
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
bool deleteLast() {
if(isEmpty())
return false;
rear=(rear-1+capacity)%capacity;
return true;
}
/** Get the front item from the deque. */
int getFront() {
if(isEmpty())
return -1;
return arr[front];
}
/** Get the last item from the deque. */
int getRear() {
if(isEmpty())
return -1;
return arr[(rear-1+capacity)%capacity];
}
/** Checks whether the circular deque is empty or not. */
bool isEmpty() {
return front ==rear;
}
/** Checks whether the circular deque is full or not. */
bool isFull() {
return (rear+1)%capacity==front;
}
};
/**
* 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();
*/