LinkQueue.h
#include<stdio.h>
#include<malloc.h>
#include<assert.h>#define ElemType int
//链式队列
typedef struct QueueNode
{
ElemType data;
struct QueueNode *next;
}QueueNode;typedef struct LinkQueue
{
QueueNode *front;
QueueNode *tail;
}LinkQueue;void InitQueue(LinkQueue *Q);
void EnQueue(LinkQueue *Q, ElemType x);
void ShowQueue(LinkQueue *Q);
void DeQueue(LinkQueue *Q);
void GetHead(LinkQueue *Q, ElemType *v);
int Length(LinkQueue *Q);
void ClearQueue(LinkQueue *Q);
void DestroyQueue(LinkQueue *Q);
LinkQueue.c
#include"LinkQueue.h"
//构造一个空队列Q
void InitQueue(LinkQueue *Q)
{//结点s相当于头结点指针
QueueNode *s = (QueueNode *)malloc(sizeof(QueueNode));
assert(s != NULL);//front和tail都是代表头结点,数据域为空,不存数据
Q->front = Q->tail = s;
Q->tail->next = NULL;
}//入队,将元素x插入队尾
void EnQueue(LinkQueue *Q, ElemType x)
{//申请一个新节点
QueueNode *s = (QueueNode *)malloc(sizeof(QueueNode));
assert(s != NULL);
s->data = x;
s->next = NULL;//尾插法插入新节点s
Q->tail->next = s;
Q->tail = s;
}//遍历队列元素
void ShowQueue(LinkQueue *Q)
{//从对头开始遍历队列
QueueNode *p = Q->front->next;
printf("Front:>");
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("<:Tail.\n");
}//出队
void DeQueue(LinkQueue *Q)
{//判断是否为空队列
if(Q->front == Q->tail)
return;
QueueNode *p = Q->front->next;
Q->front->next = p->next;
free(p);//p指向最后一个节点,置为空队列
if(p == Q->tail)
Q->tail = Q->front;
}//取出对头元素,存到v中
void GetHead(LinkQueue *Q, ElemType *v)
{//空队列直接返回
if(Q->front == Q->tail)
return;//Q-front是头结点,从开始结点取数据
QueueNode *p = Q->front->next;
*v = p->data;
}//求队列的长度,即队列的元素个数
int Length(LinkQueue *Q)
{
int len = 0;
QueueNode *p = Q->front->next; //跳过头结点
while(p != NULL)
{
len++;
p = p->next;
}
return len;
}//清空队列
void ClearQueue(LinkQueue *Q)
{
if(Q->front == Q->tail)
return;//请空队列保留头结点
QueueNode *p = Q->front->next;
while(p != NULL)
{
Q->front->next = p->next;
free(p);
p = Q->front->next;
}
Q->tail = Q->front;
}void DestroyQueue(LinkQueue *Q)
{
ClearQueue(Q);
free(Q->front);
Q->front = Q->tail = NULL;
}
main.c测试接口
#include"LinkQueue.h"
void main()
{
LinkQueue Q;
InitQueue(&Q);for(int i=1; i<=10; ++i)
{
EnQueue(&Q,i);
}
ShowQueue(&Q);
DeQueue(&Q);
DeQueue(&Q);
ShowQueue(&Q);
printf("Len = %d\n",Length(&Q));
}