用C语言实现链队列的初始化、入队、出队等操作并输出
时间: 2024-01-29 18:03:40 浏览: 81
以下是使用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 init(Queue *q) {
q->front = q->rear = (Node *)malloc(sizeof(Node));
q->front->next = NULL;
}
int is_empty(Queue *q) {
return q->front == q->rear;
}
void enqueue(Queue *q, int data) {
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
q->rear->next = new_node;
q->rear = new_node;
}
int dequeue(Queue *q) {
if (is_empty(q)) {
printf("Queue is empty!\n");
return -1;
}
Node *temp = q->front->next;
int data = temp->data;
q->front->next = temp->next;
if (temp == q->rear) {
q->rear = q->front;
}
free(temp);
return data;
}
void print_queue(Queue *q) {
if (is_empty(q)) {
printf("Queue is empty!\n");
return;
}
Node *temp = q->front->next;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Queue q;
init(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
print_queue(&q);
printf("Dequeued: %d\n", dequeue(&q));
printf("Dequeued: %d\n", dequeue(&q));
print_queue(&q);
return 0;
}
```
输出:
```
1 2 3
Dequeued: 1
Dequeued: 2
3
```
阅读全文