以下是一个使用 C 语言实现的简单循环队列示例:
#include <stdio.h>
#include <stdlib.h>#define MAX_SIZE 5// 定义循环队列结构体
typedef struct {int items[MAX_SIZE];int front, rear;
} Queue;// 初始化队列
void initQueue(Queue *q) {q->front = -1;q->rear = -1;
}// 检查队列是否为空
int isEmpty(Queue *q) {return (q->front == -1 && q->rear == -1);
}// 检查队列是否已满
int isFull(Queue *q) {return ((q->rear + 1) % MAX_SIZE == q->front);
}// 入队
void enqueue(Queue *q, int value) {if (isFull(q)) {printf("Queue is full. Cannot enqueue.\n");return;}if (isEmpty(q)) {q->front = 0;q->rear = 0;} else {q->rear = (q->rear + 1) % MAX_SIZE;}q->items[q->rear] = value;
}// 出队
int dequeue(Queue *q) {int removedItem;if (isEmpty(q)) {printf("Queue is empty. Cannot dequeue.\n");return -1;} else if (q->front == q->rear) {removedItem = q->items[q->front];q->front = -1;q->rear = -1;} else {removedItem = q->items[q->front];q->front = (q->front + 1) % MAX_SIZE;}return removedItem;
}// 获取队首元素
int peek(Queue *q) {if (isEmpty(q)) {printf("Queue is empty.\n");return -1;}return q->items[q->front];
}// 打印队列中的元素
void display(Queue *q) {if (isEmpty(q)) {printf("Queue is empty.\n");return;}int i = q->front;printf("Queue elements: ");do {printf("%d ", q->items[i]);i = (i + 1) % MAX_SIZE;} while (i != (q->rear + 1) % MAX_SIZE);printf("\n");
}int main() {Queue q;initQueue(&q);enqueue(&q, 1);enqueue(&q, 2);enqueue(&q, 3);enqueue(&q, 4);enqueue(&q, 5); // 队列已满display(&q);dequeue(&q);dequeue(&q);display(&q);enqueue(&q, 6);display(&q);printf("Front element: %d\n", peek(&q));return 0;
}
这个示例包含了循环队列的基本操作,包括初始化队列、判断队列是否为空或已满、入队、出队、获取队首元素以及打印队列中的元素。
插入新数据 删除旧数据
#include <stdio.h>#define MAX_SIZE 5// 定义队列结构
struct Queue {int items[MAX_SIZE];int front;int rear;
};// 初始化队列
void initQueue(struct Queue *q) {q->front = -1;q->rear = -1;
}// 检查队列是否已满
int isFull(struct Queue *q) {if ((q->front == 0 && q->rear == MAX_SIZE - 1) || (q->rear == (q->front - 1) % (MAX_SIZE - 1))) {return 1;}return 0;
}// 检查队列是否为空
int isEmpty(struct Queue *q) {if (q->front == -1) {return 1;}return 0;
}// 入队操作
void enqueue(struct Queue *q, int value) {if (isFull(q)) {printf("Queue is full\n");} else {if (q->front == -1) {q->front = 0;}q->rear = (q->rear + 1) % MAX_SIZE;q->items[q->rear] = value;}
}// 出队操作
int dequeue(struct Queue *q) {int item;if (isEmpty(q)) {printf("Queue is empty\n");return -1;} else {item = q->items[q->front];if (q->front == q->rear) {q->front = -1;q->rear = -1;} else {q->front = (q->front + 1) % MAX_SIZE;}return item;}
}// 打印队列中的元素
void printQueue(struct Queue *q) {int i;if (isEmpty(q)) {printf("Queue is empty\n");} else {printf("Queue contains: ");for (i = q->front; i != q->rear; i = (i + 1) % MAX_SIZE) {printf("%d ", q->items[i]);}printf("%d\n", q->items[i]);}
}int main() {struct Queue q;initQueue(&q);// 初始化队列enqueue(&q, 10);enqueue(&q, 20);enqueue(&q, 30);enqueue(&q, 40);enqueue(&q, 50);// 打印初始队列printf("Initial queue: ");printQueue(&q);// 移动队列元素并添加新元素dequeue(&q);enqueue(&q, 60);// 打印修改后的队列printf("Modified queue: ");printQueue(&q);return 0;
}