队列
队列:只可以从尾部入队,头部出队,先进先出,一个指针指向链表的头部,一个指针指向链表的尾部。
出队PopFront,入队PushRear.
队列的创建,初始化
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int Dat;
typedef struct QueNode
{
struct QueNode* next;
Dat data;
}Qn;
typedef struct QueList
{
Qn* front;
Qn* rear;
}QL;
初始化
void QueInit(QL* pq)
{
assert(pq);
pq->front = pq->rear = NULL;
}
队列的入队,出队
void QuePush(QL* pq, Dat x)
{
assert(pq);
Qn* node = (Qn*)malloc(sizeof(Qn));
if (node == NULL)
{
printf("malloc failed\n");
exit(-1);
}
node->data = x;
node->next = NULL;
//一个节点,多个节点
if (pq->rear == NULL)
{
pq->rear = pq->front = node;
}
else
{
pq->rear->next = node;
pq->rear = node;
}
}
出队
void QuePop(QL* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
if (pq->front->next == NULL)
{
free(pq->front);
//他俩指向唯一的一个节点
pq->front = pq->rear = NULL;
}
else
{
Qn* nex = pq->front->next;
free(pq->front);
pq->front = nex;
}
}
队列尾部元素,队列头部元素,队列元素个数
Dat QueRear(QL* pq)
{
assert(pq);
检测是否是空队列
assert(!QueueEmpty(pq));
return pq->rear->data;
}
队头
Dat QueFront(QL* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->front->data;
}
元素个数
int QueSize(QL* pq)
{
assert(pq);
int n = 0;
如果频繁调用这个接口函数,
可以在Queue中给一个size记录数据个数
Qn* cur = pq->front;
while (cur)
{
++n;
cur = cur->next;
}
return n;
}
队列是否为空,销毁队列
bool QueueEmpty(QL* pq)
{
assert(pq);
return pq->front == NULL && pq->rear == NULL;
}
销毁
void QueDestory(QL* pq)
{
assert(pq);
Qn* cur = pq->front;
while (cur)
{
Qn* nex = cur->next;
free(cur);
cur = nex;
}
pq->front = pq->rear = NULL;
}
队列的测试用例
队列不为空,则一直出队头元素
while (!QueueEmpty(&qu))
{
printf("%d ", QueFront(&qu));
QuePop(&qu);
}
printf("\n");
printf("队列是否为空:%d\n", QueueEmpty(&qu));
printf("队列中的有效元素个数:%d\n", QueSize(&qu));