写一个链式队列
时间: 2024-02-28 12:56:15 浏览: 44
以下是一个简单的链式队列的实现,包括队列的初始化、入队、出队和销毁等操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 队列节点定义
typedef struct queue_node {
int data; // 数据域
struct queue_node *next; // 指针域
} QueueNode;
// 队列定义
typedef struct queue {
QueueNode *front; // 队头指针
QueueNode *rear; // 队尾指针
} Queue;
// 初始化队列
void initQueue(Queue *q) {
q->front = q->rear = NULL;
}
// 销毁队列
void destroyQueue(Queue *q) {
while (q->front != NULL) {
QueueNode *p = q->front;
q->front = p->next;
free(p);
}
q->rear = NULL;
}
// 判断队列是否为空
int isQueueEmpty(Queue *q) {
return q->front == NULL;
}
// 入队操作
void enqueue(Queue *q, int data) {
QueueNode *p = (QueueNode *)malloc(sizeof(QueueNode));
p->data = data;
p->next = NULL;
if (q->rear == NULL) {
q->front = q->rear = p;
} else {
q->rear->next = p;
q->rear = p;
}
}
// 出队操作
int dequeue(Queue *q) {
if (q->front == NULL) {
printf("Queue is empty!\n");
return -1;
}
QueueNode *p = q->front;
int data = p->data;
q->front = p->next;
if (q->front == NULL) {
q->rear = NULL;
}
free(p);
return data;
}
// 测试代码
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("%d\n", dequeue(&q)); // output: 1
printf("%d\n", dequeue(&q)); // output: 2
enqueue(&q, 4);
printf("%d\n", dequeue(&q)); // output: 3
printf("%d\n", dequeue(&q)); // output: 4
printf("%d\n", dequeue(&q)); // output: Queue is empty! -1
return 0;
}
```
在上面的代码中,`QueueNode`结构体表示队列中的节点,`Queue`结构体表示队列本身,包括队头指针和队尾指针。队列的初始化使用`initQueue`函数,销毁队列使用`destroyQueue`函数,入队操作使用`enqueue`函数,出队操作使用`dequeue`函数。在`enqueue`函数中,先创建一个新节点,然后将其插入到队尾,更新队尾指针。在`dequeue`函数中,先检查队列是否为空,然后取出队头元素,更新队头指针,如果此时队列为空,则同时更新队尾指针。
相关推荐
![](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)