循环队列Circular Queue

循环队列:先进先出,从头出:front+1,从尾进:rear+1,空判断:front==rear,满判断(rear+1)%maxsize==front

//循环队列的实现

//定义队列结构体

define MAXSIZE 100

typedef struct
{
int *base; //存储内存分配基地址
int front; //队列头索引
int rear; //队列尾索引
}circularQueue;

//队列初始化
void InitQueue(circularQueue *q)
{
q->base = (int *)malloc((MAXSIZE) * sizeof(int));
if(NULL == q->base) exit(0);
q->front = q->rear = 0;
}

//入队队列
void InsertQueue(circularQueue *q, int e)
{
if((q->rear+1)%MAXSIZE == q->front) return; //队已满
q->base[q->rear] = e;
q->rear = (q->rear+1%)MAXSIZE; //尾部指向下一个空间位置,取模保证索引不越界(余数一定小于除数)
}

//出队列
void DeleteQueue(circularQueue *q, int *e)
{
if((q->front==q->end)) return;
*e = q->base[q->front];
q->front = (q->front+1)%MAXSIZE;
}

猜你喜欢

转载自www.cnblogs.com/embeddedking/p/9691981.html
今日推荐