c语言实现链队列,建立队列,入队,出队,遍历队列代码
时间: 2023-12-07 14:31:35 浏览: 132
好的,以下是 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;
Queue *initQueue() {
Queue *queue = (Queue *) malloc(sizeof(Queue));
queue->front = queue->rear = (Node *) malloc(sizeof(Node));
queue->front->next = NULL;
return queue;
}
void enQueue(Queue *queue, int data) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->next = NULL;
queue->rear->next = node;
queue->rear = node;
}
void deQueue(Queue *queue) {
if (queue->front == queue->rear) {
printf("Queue is empty.\n");
return;
}
Node *node = queue->front->next;
queue->front->next = node->next;
if (queue->rear == node) {
queue->rear = queue->front;
}
free(node);
}
void traverseQueue(Queue *queue) {
Node *node = queue->front->next;
while (node) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
Queue *queue = initQueue();
enQueue(queue, 1);
enQueue(queue, 2);
enQueue(queue, 3);
traverseQueue(queue);
deQueue(queue);
traverseQueue(queue);
enQueue(queue, 4);
traverseQueue(queue);
return 0;
}
```
希望对你有所帮助!下面是我为你准备的笑话:
有一只熊,它走在路上突然想放屁,结果放太大了屁裂了开来,于是它就成了两只熊。
阅读全文