具体代码如下:
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef int ElemType, Status;
typedef struct LNode //链式队列节点
{
ElemType data; //每个节点的数据
struct LNode* next; //指向下一个节点
}LNode, *QueuePtr;
typedef struct LinkQueue
{
QueuePtr front; //队头指针
QueuePtr rear; //队尾指针
}LinkQueue;
Status InitQueue(LinkQueue& Q) //链式队列的初始化
{
Q.front = (LNode*)malloc(sizeof(LNode));
if (Q.front == NULL) exit(0);
Q.front->next = NULL;
Q.rear = Q.front;
return OK;
}
Status DestroyQueue(LinkQueue& Q) //链式队列的销毁
{
if (Q.front == NULL) return OK;
LNode* p = Q.front;
LNode* q;
while (p)
{
q = p;
p = p->next;
free(q);
}
Q.front = NULL;
Q.rear = NULL;
return OK;
}
Status ClearQueue(LinkQueue& Q) //链式队列的清空
{
if (Q.front == NULL) return ERROR;
if (Q.front->next == NULL) return OK;
LNode* p = Q.front->next;
LNode* q;
while (p)
{
q = p;
p = p->next;
free(q);
}
Q.front->next == NULL;
Q.rear = Q.front;
return OK;
}
Status QueueEmpty(LinkQueue Q) //链式队列判空
{
if (Q.front == Q.rear) return OK;
return ERROR;
}
Status QueueLength(LinkQueue Q) //链式队列的长度
{
if (Q.front == NULL) return ERROR;
int len = 0;
LNode* p = Q.front->next;
while (p)
{
len++;
p = p->next;
}
return len;
}
Status GetHead(LinkQueue Q, ElemType& e) //链式队列获取队头元素
{
if (Q.front == NULL) return ERROR;
if (Q.front->next == NULL) return ERROR;
e = Q.front->next->data;
return OK;
}
Status QueueTraverse(LinkQueue Q) //链式队列遍历
{
if (Q.front == NULL) return ERROR;
LNode* p = Q.front->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return OK;
}
Status EnQueue(LinkQueue& Q, ElemType e) //链式队列入队
{
if (Q.front == NULL) return ERROR;
LNode* p = (LNode*)malloc(sizeof(LNode));
if (p == NULL) exit(0);
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
Status DeQueue(LinkQueue& Q, ElemType& e) //链式队列出队
{
if (Q.front == NULL) return ERROR;
if (Q.front->next == NULL) return ERROR;
e = Q.front->next->data;
LNode* p = Q.front->next;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
free(p);
return OK;
}
Status CreateQueue(LinkQueue& Q) //创建链式队列
{
InitQueue(Q);
ElemType e;
int len;
printf("队列长度:");
scanf_s("%d", &len);
printf("链式队列元素:");
int i = 0;
while (i < len)
{
scanf_s("%d", &e);
LNode* p = (LNode*)malloc(sizeof(LNode));
if (p == NULL) exit(0);
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
i++;
}
return OK;
}
int main()
{
ElemType e;
LinkQueue Q;
CreateQueue(Q);
QueueTraverse(Q);
e = 0;
EnQueue(Q, e);
QueueTraverse(Q);
GetHead(Q, e);
printf("队列长度:%d\n", QueueLength(Q));
printf("队头元素:%d\n", e);
return OK;
}
运行结果如如下: