C语音实现链队列的入队列及出队列操作。
时间: 2023-11-20 18:01:47 浏览: 36
链队列是一种基于链表实现的队列,入队列操作在队尾进行,出队列操作在队头进行。下面是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 = (Node*)malloc(sizeof(Node));
q->front->next = NULL;
}
// 判断队列是否为空
int isEmpty(Queue* q) {
return q->front == q->rear;
}
// 入队列操作
void enqueue(Queue* q, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
q->rear->next = newNode;
q->rear = newNode;
}
// 出队列操作
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
}
Node* p = q->front->next;
int data = p->data;
q->front->next = p->next;
if (q->rear == p) q->rear = q->front;
free(p);
return data;
}
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("%d ", dequeue(&q)); // output: 1
printf("%d ", dequeue(&q)); // output: 2
printf("%d ", dequeue(&q)); // output: 3
printf("%d ", dequeue(&q)); // output: Queue is empty. -1
return 0;
}
```
在上面的代码中,我们定义了两个结构体:`Node`和`Queue`。其中,`Node`表示链表的节点,`Queue`表示队列。在`Queue`结构体中,我们定义了两个指针`front`和`rear`,分别表示队头和队尾。在初始化队列时,我们让`front`和`rear`都指向一个空的节点。在入队列操作中,我们创建一个新节点,并将其插入到队尾。在出队列操作中,我们先判断队列是否为空,如果不为空则删除队头节点,并将队头指针指向下一个节点。需要注意的是,如果队列中只有一个节点,那么在出队列操作后,队头指针和队尾指针都应该指向空节点。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)