c语言实现链式存储结构的队列
时间: 2023-05-19 13:01:09 浏览: 123
可以使用指针来实现链式存储结构的队列,具体实现可以参考以下代码:
```
#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 = NULL;
}
int isEmpty(Queue* q) {
return q->front == NULL;
}
void enQueue(Queue* q, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (isEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
int deQueue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
int data = q->front->data;
Node* temp = q->front;
q->front = q->front->next;
free(temp);
return data;
}
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));
printf("%d\n", deQueue(&q));
return 0;
}
```
这段代码实现了一个基本的链式存储结构的队列,包括初始化、判断队列是否为空、入队、出队等操作。
阅读全文