#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//
typedef struct
{
int *data; // 用来指向当前队列的内存空间地址的指针
size_t length; // 数据的个数
size_t capacity; // 容量
size_t front; // 待删除数据的移动索引
size_t rear; // 添加数据后的移动索引
} Queue;
void init_queue(Queue *queue, size_t init_capacity)
{
queue->data = (int *)malloc((sizeof(int) * init_capacity));
queue->length = 0;
queue->capacity = init_capacity;
queue->front = 0;
queue->rear = 0;
}
void destroy_queue(Queue *queue)
{
free(queue->data);
queue->data = NULL;
queue->front = NULL;
queue->rear = NULL;
queue->length = 0;
queue->capacity = 0;
}
size_t get_length(Queue *queue)
{
return queue->length;
}
void en_queue(Queue *queue, int element) // 入队
{
if (queue->capacity == queue->length) // 满
{
printf("队满插入失败\n");
return;
}
queue->data[queue->rear] = element;
queue->rear = (queue->rear + 1) % queue->capacity;
queue->length++;
}
bool out_queue(Queue *queue, int *del_element)
{
if (queue->length == 0) // 空
{
return false;
}
*del_element = queue->data[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->length--;
return true;
}
void printf_queue(Queue *queue)
{
if (queue->length == 0)
return;
for (size_t i = 0; i < queue->length; i++)
{
printf("%d ", queue->data[(queue->front + i) % queue->capacity]);
}
printf("\n");
}
int main()
{
Queue q;
// 初始化
init_queue(&q, 6);
for (int i = 0; i < 7; i++)
{
en_queue(&q, 20 + i);
}
printf_queue(&q);
destroy_queue(&q);
printf_queue(&q);
}
循环队列的代码
最新推荐文章于 2024-08-22 21:24:01 发布