本帖最后由 jackz007 于 2021-10-30 19:39 编辑
改写这个函数void addStudent(struct Student**list)
【正序】void addStudent(struct Student**list)
{
struct Student * p , * p1 , * p2 ;
p=(struct Student*)malloc(sizeof(struct Student)) ;
if(p==NULL)
{
printf("内存分配失败\n");
exit(1);
}
getInput(p);
for(p1 = p2 = * list ; p1 && p1 -> average < p -> average ; p2 = p1 , p1 = p2 -> next) ;
if(p2) {
if(p1 == * list) {
p -> next = p2 ; // 新节点位于链头
* list = p ;
} else {
p -> next = p1 ; // 新节点位于链中、链尾
p2 -> next = p ;
}
} else {
p -> next = NULL ; // 新建链表
* list = p ;
}
}
【逆序】:void addStudent(struct Student**list)
{
struct Student * p , * p1 , * p2 ;
p=(struct Student*)malloc(sizeof(struct Student)) ;
if(p==NULL)
{
printf("内存分配失败\n");
exit(1);
}
getInput(p);
for(p1 = p2 = * list ; p1 && p1 -> average > p -> average ; p2 = p1 , p1 = p2 -> next) ;
if(p2) {
if(p1 == * list) {
p -> next = p2 ; // 新节点位于链头
* list = p ;
} else {
p -> next = p1 ; // 新节点位于链中、链尾
p2 -> next = p ;
}
} else {
p -> next = NULL ; // 新建链表
* list = p ;
}
}
|