开始学习队列ADT,这次弄个明晰的菜单出来。
1.问题(solved):使用switch选择执行,但读取添加、删除、全删除三个选项后就程序错误,也许是相关的三个函数有错误。
定义变量的时候错误,将变量定义成指针:
Student *temp_student=NULL;
Queue *man=NULL;
造成内存无法读取,换成:
Student temp_student={0};
Queue man={0};
程序已经可以运行。现在开始试着发现运行中的具体问题。
2.问题(solved):数据存储错误,最后一项会漏掉,进行删除等操作后甚至会报错。
显示函数:
void ShowQueue(Queue *pqueue)
{
Queue pscan=*pqueue;
fputs("*********Database*********n",stdout);
if(!pscan.nodes)
fputs("No Data Found!n",stdout);
else
{
printf("(%d)Data Found.n",pscan.nodes);
while(pscan.front)//!!!原错为(pscan.front->next)
{
printf("NO.%d:Name:%s,Score:%hd.n",
pscan.nodes,pscan.front->student.name,pscan.front->student.score);
pscan.front=pscan.front->next;
}
}
}
将原错while(pscan.front->next)改为while(pscan.front);
这个问题莫名其妙自己解决了。
3.问题(solved):显示函数的次序数有问题。总是显示最后一项。
后来终于发现:结构定义时,queue结构中的nodes计数标签存储的就是最后一项,因为queue并不是链表项,node才是链表项,所以如果要对每一项进行编码,必须在node结构里添加编码计数标签。
typedef struct student
{
char name[LEN_NAME];
short score;
}Student;
typedef struct node
{
Student student;
struct node *next;
}Node;
typedef struct queue
{
Node *front;
Node *rear;
int nodes;
}Queue;
4.问题(solved):全部删除函数的显示有错
short DeQueue(Student *pstudent,Queue *pqueue)
{
if(IsQueueEmpty(pqueue))
return 0;
Node *ptemp=pqueue->front;
*pstudent=ptemp->student;//错误原:pstudent=&(ptemp->student);
pqueue->front=pqueue->front->next;
free(ptemp);
pqueue->nodes--;
if(!(pqueue->nodes))
pqueue->rear=NULL;
return 1;}
void EmptyQueue(Student *pstudent,Queue *pqueue)
{
int i=pqueue->nodes;
while(DeQueue(pstudent,pqueue))
printf("Data->name:%s,score:%hd has cleaned.n",
pstudent->name,pstudent->score);
printf("Over!%d data has cleaned.n",i);
}
发现:错误原:pstudent=&(ptemp->student);这句代码有问题,改成:*pstudent=ptemp->student;就能顺利显示被删除数据的内容
个人理解:指向Student结构类型的指针pstudent指向ptemp->student的地址,但是ptemp内存被free(ptemp)清理,造成指向错误。
完全代码



