采用链式存储实现队列的初始化、入队、出队、销毁队列操作。
时间: 2023-05-19 11:04:21 浏览: 164
链队列存储表示及基本操作的实现.doc
好的,以下是采用链式存储实现队列的初始化、入队、出队、销毁队列操作的代码:
```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));
if (!q->front) {
printf("初始化队列失败!\n");
exit(1);
}
q->front->next = NULL;
}
void enQueue(Queue *q, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
if (!newNode) {
printf("入队失败!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
q->rear->next = newNode;
q->rear = newNode;
}
int deQueue(Queue *q) {
if (q->front == q->rear) {
printf("队列为空!\n");
exit(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;
}
void destroyQueue(Queue *q) {
while (q->front) {
Node *p = q->front;
q->front = p->next;
free(p);
}
q->rear = NULL;
}
int main() {
Queue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
printf("%d\n", deQueue(&q));
printf("%d\n", deQueue(&q));
printf("%d\n", deQueue(&q));
destroyQueue(&q);
return 0;
}
```
希望这个代码能够帮到你!
阅读全文