用代码运行链队列的基本操作
时间: 2024-05-06 19:19:29 浏览: 15
好的,以下是链队列的基本操作代码示例:
```
#include <stdio.h>
#include <stdlib.h>
// 链队列结构体
typedef struct QueueNode {
int data;
struct QueueNode *next;
} QueueNode, *QueuePtr;
typedef struct Queue {
QueuePtr front; // 队头指针
QueuePtr rear; // 队尾指针
} Queue;
// 初始化队列
void InitQueue(Queue *q) {
q->front = q->rear = (QueuePtr)malloc(sizeof(QueueNode));
q->front->next = NULL;
}
// 判断队列是否为空
int IsEmpty(Queue q) {
return q.front == q.rear;
}
// 入队
void EnQueue(Queue *q, int e) {
QueuePtr p = (QueuePtr)malloc(sizeof(QueueNode));
p->data = e;
p->next = NULL;
q->rear->next = p; // 将新节点插入到队尾
q->rear = p; // rear 指向新的队尾节点
}
// 出队
int DeQueue(Queue *q) {
if (IsEmpty(*q)) {
printf("队列为空,无法出队!\n");
return -1;
}
QueuePtr p = q->front->next; // 头指针的下一节点即为队首节点
int data = p->data; // 获取队首节点的数据
q->front->next = p->next; // 将头指针指向队首节点的下一节点
if (q->rear == p) // 如果队列只有一个节点,出队后要将 rear 指向头指针
q->rear = q->front;
free(p); // 释放出队节点
return data;
}
// 获取队头元素
int GetHead(Queue q) {
if (IsEmpty(q)) {
printf("队列为空,无法获取队头元素!\n");
return -1;
}
return q.front->next->data;
}
// 获取队列长度
int GetLength(Queue q) {
int length = 0;
QueuePtr p = q.front->next;
while (p != NULL) {
length++;
p = p->next;
}
return length;
}
int main() {
Queue q;
InitQueue(&q); // 初始化队列
// 入队
for (int i = 1; i <= 5; i++)
EnQueue(&q, i);
// 出队
for (int i = 1; i <= 5; i++)
printf("%d ", DeQueue(&q));
printf("\n");
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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://img-home.csdnimg.cn/images/20210720083646.png)