设:
队列长度是QUEUE_LENGTH
队列数组是queue[QUEUE_LENGTH]
队列头索引是head
队列尾索引是tail
队列已有元素
个数是number
入队:
queue[tail] = 元素;
tail = (tail + 1) % QUEUE_LENGTH;
number += 1;
出队:
元素 = queue[head];
head = (head + 1) % QUEUE_LENGTH;
number -= 1;
判断队列空:
if(number == 0){...}
判断队列满:
if(number >= QUEUE_LENGTH){...}
举例:
#include <stdio.h>
#include <string.h>
#define QUEUE_LENGTH 16
typedef struct {
unsigned char *data;
unsigned int size;
} SOUND_T;
typedef struct {
SOUND_T array[QUEUE_LENGTH];
unsigned head;
unsigned tail;
unsigned number;
} QUEUE_T;
//循环队列初始化
void queue_init(QUEUE_T *queue){
memset(queue, 0, sizeof(QUEUE_T));
}
//判断队列是否空
unsigned queue_isEmpty(QUEUE_T *queue){
return queue->number == 0 ? 1 : 0;
}
//判断队列是否满
unsigned queue_isFull(QUEUE_T *queue){
return queue->number >= QUEUE_LENGTH ? 1 : 0;
}
//获取队列已有成员数
unsigned queue_getNumber(QUEUE_T *queue){
return queue->number;
}
//入队
void queue_put(QUEUE_T *queue, SOUND_T *sound){
queue->array[queue->tail] = *sound;
queue->tail = (queue->tail + 1) % QUEUE_LENGTH;
queue->number += 1;
}
//出队
void queue_get(QUEUE_T *queue, SOUND_T *sound){
*sound = queue->array[queue->head];
queue->head = (queue->head + 1) % QUEUE_LENGTH;
queue->number -= 1;
}
记于 2019-02-14
网友评论