如何用c实现一个循环队列
时间: 2024-05-02 08:20:57 浏览: 45
下面是一个简单的循环队列的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5
typedef struct {
int data[MAXSIZE];
int front;
int rear;
} Queue;
Queue* createQueue() {
Queue* q = (Queue*) malloc(sizeof(Queue));
q->front = -1;
q->rear = -1;
return q;
}
int isFull(Queue* q) {
return (q->front == 0 && q->rear == MAXSIZE - 1) || (q->rear == (q->front - 1) % (MAXSIZE - 1));
}
int isEmpty(Queue* q) {
return q->front == -1;
}
void enqueue(Queue* q, int value) {
if (isFull(q)) {
printf("Queue is full.\n");
return;
}
if (q->front == -1) {
q->front = q->rear = 0;
q->data[q->rear] = value;
} else if (q->rear == MAXSIZE - 1 && q->front != 0) {
q->rear = 0;
q->data[q->rear] = value;
} else {
q->rear++;
q->data[q->rear] = value;
}
}
int dequeue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
}
int value = q->data[q->front];
q->data[q->front] = -1;
if (q->front == q->rear) {
q->front = -1;
q->rear = -1;
} else if (q->front == MAXSIZE - 1) {
q->front = 0;
} else {
q->front++;
}
return value;
}
int main() {
Queue* q = createQueue();
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 3);
enqueue(q, 4);
enqueue(q, 5);
enqueue(q, 6);
printf("Dequeued item: %d\n", dequeue(q));
printf("Dequeued item: %d\n", dequeue(q));
printf("Dequeued item: %d\n", dequeue(q));
printf("Dequeued item: %d\n", dequeue(q));
printf("Dequeued item: %d\n", dequeue(q));
printf("Dequeued item: %d\n", dequeue(q));
return 0;
}
```
这个循环队列实现了enqueue和dequeue操作。enqueue操作将元素添加到队列的尾部,dequeue操作将元素从队列的头部删除并返回。如果队列已满,则enqueue操作将不起作用,如果队列为空,则dequeue操作将不起作用。
阅读全文