假设以带头节点的循环链表表示队列,并且只设一个指针指向队尾元素节点
(注意:不设头指针) ,编写相应的置空队列、判断队列是否为空、
入队和出队等
一.初始化队列
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int CQDataType;
typedef struct CQueueNode
{
CQDataType data;
struct CQueueNode* next;
}CQNode;
typedef struct CQueue
{
CQNode* tail;
}CQueue;
//初始化
void CQueueInit(CQueue* pcq)
{
assert(pcq);
CQNode* phead = (CQNode*)malloc(sizeof(CQNode));
if (NULL == phead)
{
printf("malloc failed\n");
exit(-1);
}
phead->next = phead;
pcq->tail = phead;
}
二.入队
//入队
void CQueuePush(CQueue* pcq, CQDataType x)
{
assert(pcq);
CQNode* cur = pcq->tail;
CQNode* phead = cur->next;
CQNode* tmp = (CQNode*)malloc(sizeof(CQNode));
if (NULL == tmp)
{
printf("malloc failed\n");
exit(-1);
}
tmp->data = x;
tmp->next = phead;
cur->next = tmp;
pcq->tail = tmp;
}
三.出队
//出队
void CQueuePop(CQueue* pcq)
{
assert(pcq);
assert(pcq->tail->next != pcq->tail);
CQNode* phead = pcq->tail->next;
CQNode* cur = phead->next;
CQNode* next = cur->next;
//如果队列中只有一个数据节点,则将tail赋给哨兵位
if (phead == next)
{
pcq->tail = phead;
}
phead->next = next;
free(cur);
cur = NULL;
}
四.打印
//打印
void CQueueShow(const CQueue* pcq)
{
assert(pcq);
CQNode* phead = pcq->tail->next;
CQNode* cur = phead->next;
printf("phead->");
while (cur != phead)
{
printf("%d->", cur->data);
cur = cur->next;
}
printf("phead\n");
}
五.置空队列
//置空队列
void CQueueEmpty(CQueue* pcq)
{
assert(pcq);
assert(pcq->tail->next != pcq->tail);
CQNode* phead = pcq->tail->next;
CQNode* cur = phead->next;
while (cur != phead)
{
CQNode* next = cur->next;
free(cur);
cur = NULL;
cur = next;
}
pcq->tail = phead;
phead->next = phead;
}
六.判空
//判断队列是否为空
bool CQueueIsEmpty(const CQueue* pcq)
{
assert(pcq);
if (pcq->tail == pcq->tail->next)
{
return true;
}
else
{
return false;
}
}
七.销毁
//销毁
void CQueueDestroy(CQueue* pcq)
{
assert(pcq);
CQNode* phead = pcq->tail->next;
CQNode* cur = phead->next;
while (cur != phead)
{
CQNode* next = cur->next;
free(cur);
cur = NULL;
cur = next;
}
free(phead);
phead = NULL;
}
八.测试运行
1.代码
#include"CQueue.h"
void Test2()
{
CQueue cq;
CQueueInit(&cq);
CQueuePush(&cq, 1);
CQueuePush(&cq, 2);
CQueuePush(&cq, 3);
CQueuePush(&cq, 4);
CQueueShow(&cq);
if (CQueueIsEmpty(&cq))
{
printf("IsEmpty\n");
}
else
{
printf("IsNotEmpty\n");
}
CQueueEmpty(&cq);
CQueueShow(&cq);
if (CQueueIsEmpty(&cq))
{
printf("IsEmpty\n");
}
else
{
printf("IsNotEmpty\n");
}
CQueuePush(&cq, 1);
CQueuePush(&cq, 2);
CQueuePush(&cq, 3);
CQueueShow(&cq);
CQueueDestroy(&cq);
}
int main()
{
Test2();
return 0;
}
2.结果