622. 设计循环队列 - 力扣(LeetCode)
根据示例来看,需要设计的循环队列是满载的(不需要预留一个元素位),也就是通过设置一个tag来标志队列是否已满。
但是,将数组元素多分配一个:capacity = k + 1,那么也可以预留出一个位置来。那就采用这个办法吧。。。
至于容器使用内置数组或者vecetor都是可以的。
class MyCircularQueue {
private:
int head = 0; // 队首
int tail = 0; // 队尾的下一个
int capacity; // 容量
int *array;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
head = 0;
tail = 0;
capacity = k +1;
array = new int[capacity];
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
// 队满,插入失败
if ((tail+1) % capacity == head) return false;
array[tail] = value;
tail = (tail+1) % capacity;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
//队空,删除失败
if (head == tail) return false;
head = (head+1) % capacity;
return true;
}
/** Get the front item from the queue. */
int Front() {
if (head == tail) return -1;
return array[head];
}
/** Get the last item from the queue. */
int Rear() {
if (head == tail) return -1;
return array[(tail-1+capacity) % capacity];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return head == tail;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return (tail+1) % capacity == head;
}
};
数组换为vector也很简单:
class MyCircularQueue {
private:
int head = 0; // 队首
int tail = 0; // 队尾的下一个
int capacity; // 容量
vector<int> vec;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
head = 0;
tail = 0;
capacity = k +1;
vec.assign(capacity, 0);
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
// 队满,插入失败
if ((tail+1) % capacity == head) return false;
vec[tail] = value;
tail = (tail+1) % capacity;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
//队空,删除失败
if (head == tail) return false;
head = (head+1) % capacity;
return true;
}
/** Get the front item from the queue. */
int Front() {
if (head == tail) return -1;
return vec[head];
}
/** Get the last item from the queue. */
int Rear() {
if (head == tail) return -1;
return vec[(tail-1+capacity) % capacity];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return head == tail;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return (tail+1) % capacity == head;
}
};