用c语言写循环队列函数
时间: 2024-06-04 09:13:54 浏览: 141
以下是用c语言写循环队列函数的示例代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 100
typedef struct {
int front, rear;
int data[MAX_QUEUE_SIZE];
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isQueueEmpty(Queue *q) {
return q->front == q->rear;
}
int isQueueFull(Queue *q) {
return (q->rear + 1) % MAX_QUEUE_SIZE == q->front;
}
int enqueue(Queue *q, int value) {
if (isQueueFull(q)) {
printf("Error: queue is full\n");
return -1;
}
q->data[q->rear] = value;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
return 0;
}
int dequeue(Queue *q, int *value) {
if (isQueueEmpty(q)) {
printf("Error: queue is empty\n");
return -1;
}
*value = q->data[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return 0;
}
int main() {
Queue q;
int value;
initQueue(&q);
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
dequeue(&q, &value);
printf("%d\n", value);
dequeue(&q, &value);
printf("%d\n", value);
enqueue(&q, 40);
enqueue(&q, 50);
dequeue(&q, &value);
printf("%d\n", value);
dequeue(&q, &value);
printf("%d\n", value);
dequeue(&q, &value);
printf("%d\n", value);
return 0;
}
阅读全文