项目开发中经常使用循环队列,请制作可伸缩循环队列的静态库和动态库。至少包括以下功能: 1.创建循环队列 2.入队和出队 3.根据需要自动收缩 4.循环队列销毁 C语言代码
时间: 2023-10-30 17:44:54 浏览: 78
TIA博途-循环队列-全局FB库文件-GF-cyclic-Queue-FIFO.zip
下面是创建可伸缩循环队列的C语言代码:
//定义循环队列结构体
typedef struct {
void **buffer; //存储数据的指针数组
int head; //队首指针
int tail; //队尾指针
int length; //队列长度
int count; //队列中元素个数
} scalable_circular_queue;
//创建可伸缩循环队列
scalable_circular_queue* create_scalable_circular_queue(int length){
scalable_circular_queue* queue = (scalable_circular_queue*)malloc(sizeof(scalable_circular_queue));
queue->buffer = (void**)calloc(length, sizeof(void*));
queue->head = 0;
queue->tail = 0;
queue->length = length;
queue->count = 0;
return queue;
}
//入队
void enqueue(scalable_circular_queue* queue, void* element){
if(queue->count >= queue->length){
//队列已满,需要扩容
void** new_buffer = (void**)calloc(queue->length*2, sizeof(void*));
int i;
for(i=0; i<queue->count; i++){
new_buffer[i] = queue->buffer[(queue->head+i)%queue->length];
}
queue->head = 0;
queue->tail = queue->count;
queue->length *= 2;
free(queue->buffer);
queue->buffer = new_buffer;
}
queue->buffer[queue->tail] = element;
queue->tail = (queue->tail+1) % queue->length;
queue->count++;
}
//出队
void* dequeue(scalable_circular_queue* queue){
if(queue->count > 0){
void* element = queue->buffer[queue->head];
queue->head = (queue->head+1) % queue->length;
queue->count--;
//队列元素个数小于容量的1/4时,缩小容量
if(queue->length > 4*queue->count){
void** new_buffer = (void**)calloc(queue->count*2, sizeof(void*));
int i;
for(i=0; i<queue->count; i++){
new_buffer[i] = queue->buffer[(queue->head+i)%queue->length];
}
queue->head = 0;
queue->tail = queue->count;
queue->length = queue->count*2;
free(queue->buffer);
queue->buffer = new_buffer;
}
return element;
}
else{
return NULL;
}
}
//销毁队列
void destroy_scalable_circular_queue(scalable_circular_queue* queue){
free(queue->buffer);
free(queue);
}
//静态库和动态库的打包略。
阅读全文