用c语言实现链队列的初始化,入队和出队并在输出中展示
时间: 2024-05-02 08:16:25 浏览: 160
好的,以下是用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 *queue) {
queue->front = queue->rear = (Node *) malloc(sizeof(Node));
queue->front->next = NULL;
}
// 判断队列是否为空
int isQueueEmpty(Queue *queue) {
return queue->front == queue->rear;
}
// 入队
void enqueue(Queue *queue, int data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
queue->rear->next = newNode;
queue->rear = newNode;
}
// 出队
int dequeue(Queue *queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty!\n");
return -1;
}
Node *p = queue->front->next;
int data = p->data;
queue->front->next = p->next;
if (queue->rear == p) {
queue->rear = queue->front;
}
free(p);
return data;
}
// 输出队列中的元素
void printQueue(Queue *queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty!\n");
return;
}
Node *p = queue->front->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Queue queue;
initQueue(&queue);
printf("Enqueue: 1\n");
enqueue(&queue, 1);
printf("Enqueue: 2\n");
enqueue(&queue, 2);
printf("Enqueue: 3\n");
enqueue(&queue, 3);
printf("Queue: ");
printQueue(&queue);
printf("Dequeue: %d\n", dequeue(&queue));
printf("Dequeue: %d\n", dequeue(&queue));
printf("Dequeue: %d\n", dequeue(&queue));
printf("Queue: ");
printQueue(&queue);
return 0;
}
```
输出结果为:
```
Enqueue: 1
Enqueue: 2
Enqueue: 3
Queue: 1 2 3
Dequeue: 1
Dequeue: 2
Dequeue: 3
Queue is empty!
```
阅读全文