用C语言编写使用链式队列实现上述数据进队和出队的操作,每次进队和出队操作后需要遍历队列。
时间: 2024-03-13 21:48:05 浏览: 29
好的,我可以给你提供一个使用链式队列实现进队和出队操作的C语言代码示例,如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链式队列结构体
typedef struct Node {
int data; // 数据域
struct Node *next; // 指针域
} Node, *QueuePtr;
typedef struct {
QueuePtr front; // 队头指针
QueuePtr rear; // 队尾指针
} LinkQueue;
// 初始化链式队列
void InitQueue(LinkQueue *Q) {
Q->front = Q->rear = (QueuePtr)malloc(sizeof(Node)); // 创建头结点
if (!Q->front) {
exit(-1); // 存储分配失败
}
Q->front->next = NULL; // 头结点的指针域置为NULL
}
// 判断链式队列是否为空
int QueueEmpty(LinkQueue *Q) {
return Q->front == Q->rear; // 头尾指针相同,则队列为空
}
// 入队操作
void EnQueue(LinkQueue *Q, int e) {
QueuePtr p = (QueuePtr)malloc(sizeof(Node)); // 创建新结点
if (!p) {
exit(-1); // 存储分配失败
}
p->data = e; // 将新元素赋值给新结点的数据域
p->next = NULL; // 新结点的指针域置为NULL
Q->rear->next = p; // 将新结点挂在队尾
Q->rear = p; // 修改队尾指针
}
// 出队操作
int DeQueue(LinkQueue *Q) {
if (QueueEmpty(Q)) {
exit(-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; // 返回队头元素
}
// 遍历链式队列
void TraverseQueue(LinkQueue *Q) {
if (QueueEmpty(Q)) {
printf("队列为空\n");
return;
}
printf("链式队列中的元素为: ");
QueuePtr p = Q->front->next; // 指向队头结点
while (p != NULL) {
printf("%d ", p->data); // 输出元素值
p = p->next; // 指向下一个结点
}
printf("\n");
}
int main() {
LinkQueue Q;
InitQueue(&Q); // 初始化链式队列
EnQueue(&Q, 1); // 入队操作
EnQueue(&Q, 2);
EnQueue(&Q, 3);
TraverseQueue(&Q); // 遍历链式队列
DeQueue(&Q); // 出队操作
TraverseQueue(&Q); // 遍历链式队列
return 0;
}
```
这是一个简单的示例代码,你可以根据自己的需要进行修改和优化。
相关推荐
![](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)