简介
在实现循环队列中,如果判断队列为空以及队列是否已满。用front表示队头,rear表示队尾,len表示队列容量,当front==rear时,表示队列为空。在入队列时,rear=(rear+1)%len,当满时,rear==front,这会与判断队列为空相冲突。
少用一个存储位置
先预判断(rear+1)%len==front表示队列已满,当队列容量为1时,这种判断仍然会有问题,队列容量至少要大于1
class Queue
{
public:
Queue(int len)
{
elem = new int[len + 1];
front = 0;
rear = 0;
this->len = len + 1;
}
~Queue()
{
delete[]elem;
}
bool isEmpty()
{
return front == rear;
}
bool isFull()
{
return (rear + 1) % len == front;
}
bool push(int n)
{
if (isFull()) {
return false;
}
elem[rear] = n;
rear = (rear + 1) % len;
return true;
}
bool pop(int& n)
{
if (isEmpty()) {
return false;
}
n = elem[front];
front = (front + 1) % len;
return true;
}
private:
int* elem;
int front;
int rear;
int len;
};
使用标记
当front==rear时,使用flag来区分是队列满还是空
class Queue
{
public:
Queue(int len)
{
elem = new int[len];
front = 0;
rear = 0;
this->len = len;
flag = false;
}
~Queue()
{
delete[]elem;
}
bool isEmpty()
{
return front == rear && !flag;
}
bool isFull()
{
return front == rear && flag;
}
bool push(int n)
{
if (isFull()) {
return false;
}
elem[rear] = n;
rear = (rear + 1) % len;
if (front == rear) {
flag = true;
}
return true;
}
bool pop(int& n)
{
if (isEmpty()) {
return false;
}
n = elem[front];
front = (front + 1) % len;
if (front == rear) {
flag = false;
}
return true;
}
private:
int* elem;
int front;
int rear;
int len;
bool flag;
};
存储当前队列中的元素个数
class Queue
{
public:
Queue(int len)
{
elem = new int[len];
front = 0;
rear = 0;
this->len = len;
num = 0;
}
~Queue()
{
delete[]elem;
}
bool isEmpty()
{
return num == 0;
}
bool isFull()
{
return num == len;
}
bool push(int n)
{
if (isFull()) {
return false;
}
elem[rear] = n;
rear = (rear + 1) % len;
++num;
return true;
}
bool pop(int& n)
{
if (isEmpty()) {
return false;
}
n = elem[front];
front = (front + 1) % len;
--num;
return true;
}
private:
int* elem;
int front;
int rear;
int len;
int num;
};