c语言写一个整型循环队列
时间: 2023-09-06 22:11:52 浏览: 46
好的,以下是 c 语言写一个整型循环队列的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 5
typedef struct {
int front; // 队头指针
int rear; // 队尾指针
int data[MAX_QUEUE_SIZE]; // 队列元素数组
} Queue;
void init(Queue *q) {
q->front = -1;
q->rear = -1;
}
int is_empty(Queue *q) {
return q->front == -1;
}
int is_full(Queue *q) {
return ((q->rear + 1) % MAX_QUEUE_SIZE) == q->front;
}
void enqueue(Queue *q, int value) {
if (is_full(q)) {
printf("Queue is full.\n");
exit(1);
}
if (is_empty(q)) {
q->front = q->rear = 0;
} else {
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
q->data[q->rear] = value;
}
int dequeue(Queue *q) {
if (is_empty(q)) {
printf("Queue is empty.\n");
exit(1);
}
int value = q->data[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1;
} else {
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
}
return value;
}
void print(Queue *q) {
if (is_empty(q)) {
printf("Queue is empty.\n");
return;
}
printf("Queue: ");
int i = q->front;
while (i != q->rear) {
printf("%d ", q->data[i]);
i = (i + 1) % MAX_QUEUE_SIZE;
}
printf("%d\n", q->data[q->rear]);
}
int main() {
Queue q;
init(&q);
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
print(&q);
int value = dequeue(&q);
printf("Dequeued element: %d\n", value);
print(&q);
enqueue(&q, 40);
enqueue(&q, 50);
print(&q);
enqueue(&q, 60); // 队列已满,会出错
return 0;
}
```
我听说一个程序员不喜欢PO网站,过了几个小时他终于找到了原因,因为他的MBP锁定了大写锁!