1.初始化
CQueue* CQueueInit(int k)
{
CQueue*pq = (CQueue*)malloc(sizeof(CQueue));
(pq->a) = (int*)malloc(sizeof(int)*(k + 1));
pq->front = 0;
pq->tail = 0;
pq->CQueueSize = k;
}//k表示队列的有效数据个数
如果按需申请空间,无法判空与判满,所以需要多申请一个空间(不存放数据)
2.判空
int CQueueIsEmpty(CQueue* pq)
{
return pq->front == pq->tail ? 1 : 0;
}
3.判满
int CQueueIsFull(CQueue* pq)
{
int tailnext = pq->tail + 1;
if (tailnext == pq->CQueueSize + 1)
{
tailnext = 0;
}
return tailnext == pq->front ? 1 : 0;
}
4.入队
void CQueuePush(CQueue* pq, int value)
{
if (CQueueIsFull(pq))
{
return ;
}
(pq->a)[pq->tail] = value;
++pq->tail;
if (pq->tail == pq->CQueueSize + 1)
{
pq->tail = 0;
}
}
取模的效率(pq->tail=(pq->tail)%(pq->CQueueSize+1))低于加法的效率
5.出队
void CQueuePop(CQueue* pq)
{
if (CQueueIsEmpty(pq))
{
return ;
}
++pq->front;
if (pq->front == pq->CQueueSize + 1)
{
pq->front = 0;
}
}//取模的效率(pq->front=(pq->front)%(pq->CQueueSize+1))低于加法的效率
6.获取对头的数据
int CQueueFront(CQueue* pq)
{
if (CQueueIsEmpty(pq))
{
return ;
}
return pq->a[pq->front];
}
7.获取队尾的数据
int CQueueTail(CQueue* pq)
{
if (CQueueIsEmpty(pq))
{
return ;
}
int pretail = pq->tail - 1;
if (pretail < 0)
{
pretail = pq->CQueueSize;
}
return (pq->a)[pretail];
}
8.队列的长度
int CQueueLength(CQueue*pq)
{
int count = 0;
int cur = pq->front;
while (cur!= pq->tail)
{
++cur;
if (cur == pq->CQueueSize + 1)
{
cur = 0;
}
++count;
}
return count;
}
也就是有效数据的个数
9.打印(为了测试各个接口)
void Print(CQueue*pq)
{
if (CQueueIsEmpty(pq))
{
return;
}
int cur = pq->front;
while (cur != pq->tail)
{
printf("%2d", (pq->a)[cur]);
++cur;
if (cur == pq->CQueueSize + 1)
{
cur = 0;
}
}
printf("\n");
}
10.释放空间
void CQueueDestory(CQueue* pq)
{
free(pq->a);
pq->a = NULL;
free(pq);
pq = NULL;
}
11.测试
test()
{
//测试入队
CQueue*cq= CQueueInit(5);
CQueuePush(cq, 2);
CQueuePush(cq, 3);
CQueuePush(cq, 4);
CQueuePush(cq, 5);
CQueuePush(cq, 6);
CQueuePush(cq, 7);
Print(cq);
//测试出队
CQueuePop(cq);
CQueuePop(cq);
Print(cq);
//获取对头的数据
printf("%2d\n",CQueueFront(cq));
//获取对尾的数据
printf("%2d\n",CQueueTail(cq));
//队列的长度,即有效数据的个数
printf("%2d\n",CQueueLength(cq));
//再次打印
Print(cq);
//释放空间
CQueueDestory(cq);
cq = NULL;
}
由于传的是一级指针 ,在CQueueDestory中,即使free(pq)了,但是在主函数Queue*cq会成为野指针,所以需要将cq=NULL.
12.测试结果
队列的基本操作就分享到这里了,感谢你的浏览 。如果感兴趣的话,可以点个赞,给个关注。
( ̄▽ ̄)/
下期将发布单链表模拟实现循环队列。