简介:使用C语言实现链队列的基本操作,包括初始化、非空判断、入队列、出队列操作。此外,测试了程序的正确性。
头文件LinkQueue.h:包含数据类型定义、函数声明
#ifndef LINK_QUEUE_H
#define LINK_QUEUE_H
#include "stdio.h"
#include "stdlib.h"
typedef int ElemType;
typedef enum{
FALSE,
TRUE
}BOOL;
typedef struct LinkNode{
ElemType data;
struct LinkNode *next;
}LinkNode;
typedef struct{
LinkNode *front,*rear;
}LinkQueue;
void InitQueue(LinkQueue *Q);
BOOL IsEmpty(LinkQueue Q);
void EnQueue(LinkQueue *Q, ElemType e);
BOOL DeQueue(LinkQueue *Q, ElemType *e);
#endif
源文件LinkQueue.c:包含队列基本操作的C语言实现
#include "LinkQueue.h"
void InitQueue(LinkQueue *Q)
{
Q->front = (LinkNode *)malloc(sizeof(LinkNode));
Q->rear = Q->front;
Q->front->next = NULL;
}
BOOL IsEmpty(LinkQueue Q)
{
return (BOOL)(Q.front == Q.rear || Q.front == NULL);
}
void EnQueue(LinkQueue *Q, ElemType e)
{
LinkNode *s = (LinkNode *)malloc(sizeof(LinkNode)); //生成新结点
s->data = e;
s->next = NULL; //新节点作为最后一个结点,指针域为NULL
Q->rear->next = s; //新结点插入到rear之后
Q->rear = s; //修改表尾指针
}
BOOL DeQueue(LinkQueue *Q, ElemType *e)
{
LinkNode *p = Q->front->next;
if (Q->front == Q->rear){ //判断队列非空
return FALSE;
}
*e = p->data; //用e返回队头元素
Q->front->next = p->next; //修改头节点的next指针
if (p == Q->rear){ //此次是最后一个结点出队,设置队列为空
Q->rear = Q->front;
}
free(p); //释放结点空间
return TRUE;
}
主函数Main.c:包含测试程序
#include "stdio.h"
#include "stdlib.h"
#include "LinkQueue.h"
#define ENTRY_QUEUE_NUM 5
#define DELETE_QUEUE_NUM 3
void PrintLinkQueueAllElem(LinkQueue Q)
{
int num = 1;
LinkNode *s = Q.front->next;
if (IsEmpty(Q))
{
printf("链队列为空n");
return;
}
while (s)
{
printf("第%d个结点元素值为%dn", num, s->data);
num++;
s = s->next;
}
}
void TestLinkQueue(void)
{
int i;
ElemType e;
LinkQueue Q;
InitQueue(&Q); //初始化队列
printf("正在进行入队列操作...n");
for (i = 0; i < ENTRY_QUEUE_NUM; i++)
{
EnQueue(&Q, i+1);
}
printf("n打印队列中的所有元素...n");
PrintLinkQueueAllElem(Q);
printf("n正在进行出队列操作...n");
for (i = 0; i < DELETE_QUEUE_NUM; i++)
{
if (DeQueue(&Q, &e)){
printf("出队列成功,出队元素值为%dn", e);
}
else{
printf("出栈失败,队列为空n");
}
}
printf("n打印队列中的所有元素...n");
PrintLinkQueueAllElem(Q);
}
int main(void)
{
TestLinkQueue();
system("pause");
return 0;
}
程序运行结果:



