你可以给出C语言链队列的创立代码吗
时间: 2024-05-14 15:11:56 浏览: 13
当然可以,下面是C语言链队列的创立代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 链队列结构体
typedef struct node {
int data; // 数据域
struct node* next; // 指针域
} QueueNode;
typedef struct {
QueueNode* front; // 队头指针
QueueNode* rear; // 队尾指针
} LinkQueue;
// 初始化队列
void InitQueue(LinkQueue* Q) {
Q->front = Q->rear = (QueueNode*)malloc(sizeof(QueueNode)); // 初始时队头和队尾都指向头结点
if (!Q->front) {
printf("内存分配失败!\n");
exit(0);
}
Q->front->next = NULL;
}
// 入队
void EnQueue(LinkQueue* Q, int x) {
QueueNode* p = (QueueNode*)malloc(sizeof(QueueNode));
if (!p) {
printf("内存分配失败!\n");
exit(0);
}
p->data = x;
p->next = NULL;
Q->rear->next = p; // 把新结点插入到队尾
Q->rear = p; // 队尾指针指向新结点
}
// 出队
int DeQueue(LinkQueue* Q) {
if (Q->front == Q->rear) { // 队列为空
printf("队列为空!\n");
exit(0);
}
QueueNode* p = Q->front->next; // p指向队头结点
int x = p->data; // 取出队头结点的数据
Q->front->next = p->next; // 把队头结点从链表中删除
if (Q->rear == p) { // 如果队头结点是队尾结点,则修改队尾指针
Q->rear = Q->front;
}
free(p); // 释放队头结点的空间
return x; // 返回队头元素
}
// 判断队列是否为空
int IsEmpty(LinkQueue Q) {
return Q.front == Q.rear;
}
// 输出队列元素
void PrintQueue(LinkQueue Q) {
if (Q.front == Q.rear) {
printf("队列为空!\n");
return;
}
QueueNode* p = Q.front->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkQueue Q;
InitQueue(&Q);
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
PrintQueue(Q);
DeQueue(&Q);
PrintQueue(Q);
EnQueue(&Q, 4);
PrintQueue(Q);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)