对于循环队列,求队列含有多少个元素的算法如下:
typedef struct
{
int tail,head;
int a[Max];
}queue;
void enqueue(int key,queue&q)
{
q.a[q.tail]=key;
q.tail=(q.tail+1)%Max;
}
int dequeue(queue&q)
{
int key;
key=q.a[q.head];
q.head=(q.head+1)%Max;
return key;
}
扩展资料:
计算循环队列的元素个数:(尾-头+表长)%表长
队列头指针为来front,队列尾指针为rear,队列容量为M,则元素个数为|rear-front+M|%M,注意,这个自%是求余运算。
设f为队头,r为队尾,m为队长,a为元素个数,则1. f>r时,a=m+r-f; 2. f<=r时,a=r-f