1 循环数组队列
1.1 队列定义
#ifndef OTHER_TASK_LOOP_QUEUE_H_
#define OTHER_TASK_LOOP_QUEUE_H_
#include <stdio.h>
#define DATA_LEN 512
typedef struct {
float data[DATA_LEN];
int front;
int rear;
int capacity;
}loop_queue_t;
void init_loop_queue(loop_queue_t *queue, int capacity);
int full_loop_queue(loop_queue_t *queue);
int empty_loop_queue(loop_queue_t *queue);
int enter_loop_queue(loop_queue_t *queue, float dat);
int out_loop_queue(loop_queue_t *queue, float *dat);
int get_loop_queue_average(loop_queue_t * queue, float * avg);
int get_queue_rate(loop_queue_t * queue,float coef, float * rate);
int show_loop_queue(loop_queue_t * queue);
#endif
1.2 循环队列实现
#include <stdio.h>
#include "loop_queue.h"
void init_loop_queue(loop_queue_t *queue, int capacity)
{
if((capacity > (DATA_LEN-1)) || (capacity < 0)){
queue->capacity = DATA_LEN-1;
}else{
queue->capacity = capacity+1;
}
queue->front = 0;
queue->rear = 0;
return;
}
int full_loop_queue(loop_queue_t *queue)
{
if(queue->front == (queue->rear+1)%(queue->capacity)){
return 1;
}else{
return 0;
}
}
int empty_loop_queue(loop_queue_t *queue)
{
if(queue->front == queue->rear){
return 1;
}else{
return 0;
}
}
int enter_loop_queue(loop_queue_t *queue, float dat)
{
if(full_loop_queue(queue) == 1){
return 1;
}else{
queue->data[queue->rear] = dat;
queue->rear = (queue->rear+1)%(queue->capacity);
}
return 0;
}
int out_loop_queue(loop_queue_t *queue, float *dat)
{
if(empty_loop_queue(queue)){
return 1;
}else{
*dat = queue->data[queue->front];
queue->front = (queue->front+1)%(queue->capacity);
}
return 0;
}
int get_loop_queue_average(loop_queue_t * queue,float * avg)
{
int index = queue->front;
float sum = 0;
for(int i = 0; i < (queue->capacity-1); i++){
sum += queue->data[index];
if(index == queue->rear){
break;
}
index = (index+1)%queue->capacity;
}
*avg = sum/(queue->capacity-1);
return 0;
}
int get_queue_rate(loop_queue_t * queue,float coef, float * rate)
{
float first = queue->data[queue->front];
float last = queue->data[queue->rear];
*rate = coef*(last - first);
return 0;
}
int show_loop_queue(loop_queue_t * queue)
{
int index = queue->front;
for(int i = 0; i < queue->capacity-1; i++){
printf("%0.2f ", queue->data[index]);
if(index == queue->rear){
break;
}
index = (index+1)%queue->capacity;
}
putchar(10);
return 0;
}
int loop_queue_size(loop_queue_t * queue)
{
return (queue->rear - queue->front + queue->capacity)%(queue->capacity);
}
1.3 main函数调用测试
#include<stdio.h>
#include "loop_queue.h"
int main()
{
loop_queue_t queue;
float avg;
float data;
init_loop_queue(&queue, 10);
for(int i = 0; i < 20; i++){
enter_loop_queue(&queue, i);
}
show_loop_queue(&queue);
get_loop_queue_average(&queue, &avg);
printf("avg:%0.3f \n", avg);
for(int i = 10; i < 20; i++){
out_loop_queue(&queue, &data);
enter_loop_queue(&queue, i);
show_loop_queue(&queue);
get_loop_queue_average(&queue, &avg);
printf("avg:%0.3f \n", avg);
}
return 0;
}
1.4 输出结果
|