c语言写一个整型循环队列
时间: 2023-09-12 12:03:45 浏览: 104
好的,我可以回答这个问题。下面是一个简单的 C 语言代码示例,用于实现整型循环队列:
```
#include <stdio.h>
#define MAX_SIZE 5
int queue[MAX_SIZE];
int rear = -1, front = -1;
void enqueue(int num) {
if ((front == 0 && rear == MAX_SIZE - 1) || (rear == front - 1)) {
printf("Queue is full!\n");
return;
}
if (front == -1) front = 0;
rear = (rear + 1) % MAX_SIZE;
queue[rear] = num;
}
int dequeue() {
int num;
if (front == -1) {
printf("Queue is empty!\n");
return -1;
}
num = queue[front];
if (front == rear) {
front = -1;
rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}
return num;
}
void display() {
int i;
if (front == -1) {
printf("Queue is empty!\n");
return;
}
printf("Queue elements are:\n");
for (i = front; i != rear; i = (i + 1) % MAX_SIZE)
printf("%d ", queue[i]);
printf("%d\n", queue[i]);
}
int main() {
int choice, num;
do {
printf("1.Enqueue\n");
printf("2.Dequeue\n");
printf("3.Display\n");
printf("4.Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to be enqueued: ");
scanf("%d", &num);
enqueue(num);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Invalid choice!\n");
break;
}
} while (choice != 4);
return 0;
}
```
这段代码实现了一个整型循环队列,可以通过命令行交互来进行入队、出队和显示队列元素等操作。
阅读全文