用c语言实现个简单的队列的链式存储
时间: 2024-02-05 11:10:27 浏览: 78
以下是用 C 语言实现简单的队列的链式存储:
```c
#include <stdio.h>
#include <stdlib.h>
// 队列节点结构体
typedef struct queueNode {
int data;
struct queueNode *next;
} QueueNode;
// 队列结构体
typedef struct queue {
QueueNode *front; // 队头指针
QueueNode *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) {
QueueNode *newNode = (QueueNode *)malloc(sizeof(QueueNode));
newNode->data = data;
newNode->next = NULL;
if (q->rear == NULL) {
q->rear = q->front = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
// 出队
int deQueue(Queue *q) {
if (isEmpty(q)) {
printf("队列为空\n");
exit(1);
}
int data = q->front->data;
QueueNode *temp = q->front;
q->front = q->front->next;
free(temp);
if (q->front == NULL) {
q->rear = NULL;
}
return data;
}
// 打印队列
void printQueue(Queue *q) {
if (isEmpty(q)) {
printf("队列为空\n");
return;
}
QueueNode *temp = q->front;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Queue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
printQueue(&q);
printf("出队元素:%d\n", deQueue(&q));
printf("出队元素:%d\n", deQueue(&q));
printQueue(&q);
enQueue(&q, 4);
enQueue(&q, 5);
printQueue(&q);
return 0;
}
```
这里使用了队列节点结构体和队列结构体,初始化队列时,将队头指针和队尾指针都赋为 NULL;判断队列是否为空时,只需判断队头指针是否为 NULL。入队操作时,新建一个节点,并将其链接在队尾,同时更新队尾指针;出队操作时,将队头节点删除,并将队头指针指向下一个节点,同时更新队尾指针。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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)