这里用变量qsize来指示队列中含有多少个元素,判断队列满或空。在编码的时候要注意数组下标的边界就好了。
注意一点:自己因为很长时间不写c++对c++的语法不是很熟了,新建一个动态int数组为new int[length_of_the_array] 而 new int(int_value)是new一个int数,值为int_value,让我找了好长时间才发现这个错误555.
class MyCircularQueue
{
public:
int head;
int rear;
int num;
int qsize;
int* qu;
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k)
{
head=0;
rear=0;
qsize=0;
num=k;
qu=new int[k];
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value)
{
if(qsize==num)
{
return false;
}
else
{
qu[rear]=value;
rear=(rear+1)%num;
qsize++;
return true;
}
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue()
{
if(qsize==0)
{
return false;
}
else
{
head=(head+1)%num;
qsize--;
return true;
}
}
/** Get the front item from the queue. */
int Front()
{
if(qsize==0)
{
return -1;
}
else
{
return qu[head];
}
}
/** Get the last item from the queue. */
int Rear()
{
if(qsize==0)
{
return -1;
}
else
{
int loc=rear-1;
if(loc<0)
loc=num-1;
return qu[loc];
}
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty()
{
if(qsize>0)
{
return false;
}
else
{
return true;
}
}
/** Checks whether the circular queue is full or not. */
bool isFull()
{
if(qsize==num)
{
return true;
}
else
{
return false;
}
}
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue* obj = new MyCircularQueue(k);
* bool param_1 = obj->enQueue(value);
* bool param_2 = obj->deQueue();
* int param_3 = obj->Front();
* int param_4 = obj->Rear();
* bool param_5 = obj->isEmpty();
* bool param_6 = obj->isFull();
*/
来源:CSDN
作者:JLUspring
链接:https://blog.csdn.net/qq_37724465/article/details/104311130