Linux C 实现循环队列
时间: 2023-07-12 14:46:40 浏览: 75
在 Linux C 中,可以使用指针和结构体来实现循环队列数据结构。下面是一个简单的循环队列实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define QUEUE_SIZE 10
typedef struct {
int front, rear;
int items[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) % QUEUE_SIZE == q->front;
}
void enqueue(Queue *q, int value) {
if (is_full(q)) {
printf("Queue overflow\n");
exit(EXIT_FAILURE);
}
if (is_empty(q)) {
q->front = 0;
}
q->rear = (q->rear + 1) % QUEUE_SIZE;
q->items[q->rear] = value;
}
int dequeue(Queue *q) {
int value;
if (is_empty(q)) {
printf("Queue underflow\n");
exit(EXIT_FAILURE);
}
value = q->items[q->front];
if (q->front == q->rear) {
q->front = -1;
q->rear = -1;
} else {
q->front = (q->front + 1) % QUEUE_SIZE;
}
return value;
}
int main() {
Queue q;
init(&q);
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
printf("%d ", dequeue(&q));
printf("%d ", dequeue(&q));
printf("%d ", dequeue(&q));
return 0;
}
```
在这个例子中,我们定义了一个带有 `front` 和 `rear` 属性的 `Queue` 结构体,以及检查队列是否为空或已满的函数。 `enqueue()` 函数将元素添加到队列的末尾,而 `dequeue()` 函数将元素从队列的开头移除并返回它。我们还使用 `init()` 函数来初始化队列。与普通队列不同的是,循环队列中的 `front` 和 `rear` 指针在达到队列末尾时会回到队列的开头,从而形成循环。