计算循环队列的长度
实现函数:
//计算队列长度
int len_queue(queue_list list)
{
if(NULL == list || list->front == list->rear)
{
printf("ERROR\n");
return -1;
}
int len = 0;
int front = 0;
int rear = 0;
for(int i = list->front ; i <MAXSIZE-1 ; i = (i+1)%MAXSIZE)
{
front++;
}
for(int i = 0 ; i <= list->rear ; i = (i+1)%MAXSIZE)
{
rear++;
}
len = (front + rear)%MAXSIZE;
return len;
}
主函数:
queue_list list = create();
int element = 0;
char str[10] = "";
//插入
do
{
printf("请输入插入的值:");
scanf("%d",&element);
loop_enqueue(list,element);
printf("是否继续? yes/no:");
scanf("%s",str);
}while(strcmp(str,"no"));
//遍历输出
printf("遍历输出:\n");
loop_output(list);
//计算队列长度
int len = len_queue(list);
if(len == -1)
{
printf("ERROR\n");
}
else
{
printf("队列长度=%d\n",len);
}
//删除
do
{
loop_delqueue(list);
printf("是否继续? yes/no:");
scanf("%s",str);
}while(strcmp(str,"no"));
printf("遍历输出:\n");
loop_output(list);
//计算队列长度
len = len_queue(list);
if(len == -1)
{
printf("ERROR\n");
}
else
{
printf("队列长度=%d\n",len);
}
运行结果:
Xmind: