编写c语言代码实现循环队列
时间: 2024-06-12 20:11:37 浏览: 120
为了实现循环队列,我们需要定义一个数组和两个指针front和rear。front指向队列的第一个元素,rear指向队列的最后一个元素。当队列为空时,front和rear都指向-1。当队列满时,rear指向最后一个元素,front指向第一个元素的前一个位置。下面是一个简单的C语言实现循环队列的代码:
```
#define MAX_SIZE 10
int queue[MAX_SIZE];
int front = -1, rear = -1;
void enqueue(int data) {
if ((front == 0 && rear == MAX_SIZE - 1) || (rear == front - 1)) {
printf("Queue is full\n");
return;
}
else if (front == -1 && rear == -1) {
front = rear = 0;
}
else if (rear == MAX_SIZE - 1 && front != 0) {
rear = 0;
}
else {
rear++;
}
queue[rear] = data;
}
int dequeue() {
if (front == -1 && rear == -1) {
printf("Queue is empty\n");
return -1;
}
int data = queue[front];
if (front == rear) {
front = rear = -1;
}
else if (front == MAX_SIZE - 1) {
front = 0;
}
else {
front++;
}
return data;
}
```
阅读全文