【发布时间】:2022-01-23 11:44:08
【问题描述】:
我设计了一个提供队列管理系统的循环队列程序。一切正常,除了在某些情况下,我无法打印队列。
我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define CAPACITY 5
#define MAX_STRING_SIZE 40
#define TRUE 1
#define FALSE 0
struct queue
{
char items[CAPACITY][MAX_STRING_SIZE];
int front,rear ;
};
void cqinsert(struct queue * , char name[]);
void cqdelete(struct queue *);
int empty(struct queue *);
int main(void)
{
int order;
char name[MAX_STRING_SIZE];
int menu;
char operation;
int x;
struct queue q;
q.front = q.rear = CAPACITY - 1;
do{
printf(">>Please enter an operation number from the given list:\n");
printf("[1]-Customer Entry\n[2]-Customer Exit\n[3]-Waiting Customers List\n[4]-Exit\n");
scanf("%d",&menu);
switch(menu) {
case 1: printf("Enter customer name: ");
scanf("%s",&name);
cqinsert(&q,name);
break;
case 2: cqdelete(&q);
break;
case 3: if(q.front==CAPACITY-1) {
order = 1;
for(int i=0;i<=q.rear;i++) {
printf("[%d]-%s\n",order,q.items[i]);
order++;
}
break;
}
else {
order=1;
for(int i=q.front+1;i<=q.rear;i++) {
printf("[%d]-%s\n",order,q.items[i]);
order++;
}
break;
}
}
}while(menu!=4);
system("pause");
return 0;
}
int empty(struct queue *pq)
{
return((pq->front == pq->rear) ? TRUE : FALSE);
}
void cqdelete(struct queue *pq)
{
if (empty(pq)) {
printf("Queue is empty !");
exit(1);
}
if (pq->front == CAPACITY - 1)
pq->front = 0;
else
(pq->front)++;
printf("\n -----> %s is deleted from the queue. \n\n",pq->items[pq->front]);
}
void cqinsert(struct queue *pq , char name[])
{
printf("\n -----> %s is inserted to queue. \n\n",name);
if (pq->rear == CAPACITY - 1)
pq->rear = 0;
else
(pq->rear)++;
if (pq->rear == pq->front) {
printf("Queue is full !");
exit(1);
}
strcpy(pq->items[pq->rear],name);
}
当q.front 大于q.rear 时,case 3(打印)不会打印任何内容。
例如在下面的输入之后我无法显示队列元素:
- 4 次客户输入(插入)
- 2 次 CUSTOMER EXIT(delete)
- 2 次客户输入(插入)
- 并选择Waiting Customers List ---> 问题是:它不显示队列中的元素。
您可以使用以下输入来应用这些步骤:
1
c1
1
c2
1
c3
1
c4
2
2
1
c5
1
c6
3
4
即使q.front 大于q.rear,我如何才能显示队列?
【问题讨论】: