在C语言中,链式队列可以使用链表数据结构来实现。队列是一种特殊的线性表,只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。这种操作规则使队列没有上溢问题,但存在下溢的可能。
以下是一个简单的链式队列的实现:
c
#include <stdio.h> | |
#include <stdlib.h> | |
// 定义队列节点 | |
typedef struct QueueNode { | |
int data; | |
struct QueueNode* next; | |
} QueueNode, *QueuePtr; | |
// 定义队列 | |
typedef struct { | |
QueuePtr front; // 队头指针 | |
QueuePtr rear; // 队尾指针 | |
} LinkQueue; | |
// 初始化队列 | |
void InitQueue(LinkQueue* Q) { | |
Q->front = Q->rear = (QueuePtr)malloc(sizeof(QueueNode)); | |
if (!Q->front) { | |
exit(0); | |
} | |
Q->front->next = NULL; | |
} | |
// 判断队列是否为空 | |
int QueueEmpty(LinkQueue Q) { | |
return Q.front == Q.rear; | |
} | |
// 入队操作 | |
void EnQueue(LinkQueue* Q, int e) { | |
QueuePtr p = (QueuePtr)malloc(sizeof(QueueNode)); | |
if (!p) { | |
exit(0); | |
} | |
p->data = e; | |
p->next = NULL; | |
Q->rear->next = p; | |
Q->rear = p; | |
} | |
// 出队操作 | |
int DeQueue(LinkQueue* Q) { | |
if (QueueEmpty(*Q)) { | |
return -1; // 队列为空,返回错误码 | |
} | |
QueuePtr p = Q->front->next; | |
int e = p->data; | |
Q->front->next = p->next; | |
if (Q->rear == p) { | |
Q->rear = Q->front; | |
} | |
free(p); | |
return e; | |
} | |
int main() { | |
LinkQueue Q; | |
InitQueue(&Q); | |
// 入队几个元素 | |
EnQueue(&Q, 1); | |
EnQueue(&Q, 2); | |
EnQueue(&Q, 3); | |
// 出队并打印元素 | |
while (!QueueEmpty(Q)) { | |
printf("%d ", DeQueue(&Q)); | |
} | |
return 0; | |
} | |
这个程序首先定义了一个队列节点结构和一个队列结构。队列结构包括队头指针和队尾指针。然后,我们实现了初始化队列、判断队列是否为空、入队和出队等基本操作。在main函数中,我们创建了一个队列,并进行了入队和出队操作。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论