可以用c写一个链队列吗?
时间: 2024-05-07 17:17:47 浏览: 15
是的,可以用C语言来实现链队列。
链队列是一种基于链表的队列实现方式。它与顺序队列不同,链队列的存储空间是动态分配的。链队列的队头和队尾分别对应链表的头结点和尾结点。
下面是一个简单的链队列的实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链队列结点
typedef struct Node
{
int data;
struct Node *next;
} Node;
// 定义链队列
typedef struct Queue
{
Node *front; // 队头指针
Node *rear; // 队尾指针
} Queue;
// 初始化队列
void initQueue(Queue *q)
{
q->front = q->rear = NULL;
}
// 判断队列是否为空
int isEmpty(Queue *q)
{
return (q->front == NULL);
}
// 入队操作
void enqueue(Queue *q, int data)
{
Node *p = (Node *)malloc(sizeof(Node));
if (p == NULL) // 内存分配失败
{
printf("Memory allocation failed.\n");
return;
}
p->data = data;
p->next = NULL;
if (isEmpty(q))
{
q->front = q->rear = p;
}
else
{
q->rear->next = p;
q->rear = p;
}
}
// 出队操作
int dequeue(Queue *q)
{
if (isEmpty(q)) // 队列为空
{
printf("Queue is empty.\n");
return -1;
}
int data = q->front->data;
Node *p = q->front;
q->front = q->front->next;
free(p); // 释放结点内存
return data;
}
// 遍历队列
void traverseQueue(Queue *q)
{
if (isEmpty(q)) // 队列为空
{
printf("Queue is empty.\n");
return;
}
Node *p = q->front;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
traverseQueue(&q);
dequeue(&q);
traverseQueue(&q);
return 0;
}
```
在这个实现中,我们使用了两个结构体:`Node`和`Queue`。`Node`结构体用于表示链队列中的结点,其中包含一个`data`字段用于存储数据,以及一个`next`指针用于指向下一个结点。`Queue`结构体则用于表示链队列本身,其中包含两个指针`front`和`rear`,分别指向队头和队尾。
链队列中的入队操作是通过动态分配一个新的结点并将其加入到队列的尾部来实现的。而出队操作则是删除队列的头结点,并返回其存储的数据。遍历队列则是从队头开始遍历整个队列,并输出每个结点的数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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://csdnimg.cn/download_wenku/file_type_ask_c1.png)