c语言循环队列实现入队出队
时间: 2023-10-24 20:06:30 浏览: 177
循环队列是一种常用的队列实现方式,可以利用数组来实现。下面是C语言中循环队列的入队和出队操作的实现示例:
```c
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isEmpty(Queue *q) {
return q->front == q->rear;
}
int isFull(Queue *q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}
void enqueue(Queue *q, int item) {
if (isFull(q)) {
printf("Queue is full\n");
return;
}
q->data[q->rear] = item;
q->rear = (q->rear + 1) % MAX_SIZE;
}
int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return -1; // or any other value to indicate an error
}
int item = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return item;
}
```
使用示例:
```c
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
printf("%d\n", dequeue(&q));
return 0;
}
```
输出结果:
```
1
2
3
```
阅读全文