//队列基本实现
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue* queue) {
queue->front = 0;
queue->rear = -1;
}
int isFull(Queue* queue) {
return (queue->rear == MAX_SIZE - 1);
}
int isEmpty(Queue* queue) {
return (queue->rear < queue->front);
}
void enqueue(Queue* queue, int item) {
if (isFull(queue)) {
printf("Queue is full\n");
return;
}
queue->data[++queue->rear] = item;
}
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
int item = queue->data[queue->front++];
return item;
}
int main() {
Queue queue;
initQueue(&queue);
enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
printf("Dequeued item: %d\n", dequeue(&queue));
printf("Dequeued item: %d\n", dequeue(&queue));
printf("Dequeued item: %d\n", dequeue(&queue));
return 0;
}
//循环队列
#include <stdio.h>
#include <stdbool.h>
#define MAX_QUEUE_SIZE 100
typedef struct {
int data[MAX_QUEUE_SIZE];
int front;
int rear;
} CircularQueue;
// 初始化循环队列
void initQueue(CircularQueue* queue) {
queue->front = 0;
queue->rear = 0;
}
// 判断队列是否为空
bool isEmpty(CircularQueue* queue) {
return queue->front == queue->rear;
}
// 判断队列是否已满
bool isFull(CircularQueue* queue) {
return (queue->rear + 1) % MAX_QUEUE_SIZE == queue->front;
}
// 入队
void enqueue(CircularQueue* queue, int value) {
if (isFull(queue)) {
printf("Queue is full. Unable to enqueue.\n");
return;
}
queue->rear = (queue->rear + 1) % MAX_QUEUE_SIZE;
queue->data[queue->rear] = value;
}
// 出队
int dequeue(CircularQueue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty. Unable to dequeue.\n");
return -1; // 返回一个特殊值表示出错
}
queue->front = (queue->front + 1) % MAX_QUEUE_SIZE;
int value = queue->data[queue->front];
return value;
}
// 获取队头元素
int front(CircularQueue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1; // 返回一个特殊值表示出错
}
int frontIndex = (queue->front + 1) % MAX_QUEUE_SIZE;
int value = queue->data[frontIndex];
return value;
}
// 获取队列长度
int size(CircularQueue* queue) {
return (queue->rear - queue->front + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE;
}
int main() {
CircularQueue queue;
initQueue(&queue);
// 入队操作
enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
// 出队操作
int value = dequeue(&queue);
printf("Dequeued element: %d\n", value);
// 获取队头元素
int frontValue = front(&queue);
printf("Front element: %d\n", frontValue);
// 获取队列长度
int queueSize = size(&queue);
printf("Queue size: %d\n", queueSize);
return 0;
}
队列的实现方式有两种这里是使用数组来实现,顺序队列实现和循环队列,循环队列解决了顺序队列浪费空间的问题,队列特点时在队列尾部进行加入,在队列头部进行删除操作,所以当删除操作进行后,数组有空出来的位置,但是数据只能在队列尾部进行插入所以这部分被队列释放的空间不可用,为了解决这个问题循环队列采用动态取模来修改队头,队尾的值来进行循环利用被队列释放的空间。
front和rear可以设置为-1,这样数组中可以从0索引就开始填充,使用取余的形式来给front和rear赋值是为了在到达数组最大索引位置时能够回到数组开头索引,具体来讲当添加数据时从数组0索引出开始添加,添加到数组末尾处队列处于满员。当从队列中删除元素时从0处开始删除,并且修改front的值+1,这样当再次判断是否队列full,就可以return (queue->rear + 1) % MAX_QUEUE_SIZE == queue->front;返回false同理当front走到数组最大索引处,取余运算同样会使得front回归到索引为0的位置来读取0索引上的数据。