编写一段关于队列的C语言代码
时间: 2023-10-25 08:12:12 浏览: 71
以下是一个简单的队列实现的 C 语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int front, rear;
int data[MAX_SIZE];
} Queue;
Queue *createQueue() {
Queue *queue = (Queue *) malloc(sizeof(Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}
int isFull(Queue *queue) {
return queue->rear == MAX_SIZE - 1;
}
int isEmpty(Queue *queue) {
return queue->front == -1 || queue->front > queue->rear;
}
void enqueue(Queue *queue, int value) {
if (isFull(queue)) {
printf("Queue is full\n");
return;
}
queue->data[++queue->rear] = value;
if (queue->front == -1) {
queue->front = 0;
}
}
int dequeue(Queue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
int value = queue->data[queue->front++];
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return value;
}
int main() {
Queue *queue = createQueue();
enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
printf("%d dequeued from queue\n", dequeue(queue));
printf("%d dequeued from queue\n", dequeue(queue));
enqueue(queue, 40);
enqueue(queue, 50);
printf("%d dequeued from queue\n", dequeue(queue));
printf("%d dequeued from queue\n", dequeue(queue));
printf("%d dequeued from queue\n", dequeue(queue));
return 0;
}
```
这段代码实现了一个基本的队列,包括创建队列、判断队列是否为空、判断队列是否已满、入队、出队等基本操作。
阅读全文