void *Sort(STU *head) { p = head->next; now = head; pr = head; while (p != NULL) { while (p->next != NULL) { if ((p->score[0] + p->score[1] + p->score[2]) < (p->next->score[0] + p->next->score[1] + p->next->score[2])) { strcpy(pr->num, p->num); strcpy(pr->name, p->name); strcpy(pr->major, p->major); pr->classNo = p->classNo; pr->score[0] = p->score[0]; pr->score[1] = p->score[1]; pr->score[2] = p->score[2]; strcpy(p->num, p->next->num); strcpy(p->name, p->next->name); strcpy(p->major, p->next->major); p->classNo = p->next->classNo; p->score[0] = p->next->score[0]; p->score[1] = p->next->score[1]; p->score[2] = p->next->score[2]; strcpy(p->next->num, pr->num); strcpy(p->next->name, pr->name); strcpy(p->next->major, pr->major); p->next->classNo = pr->classNo; p->next->score[0] = pr->score[0]; p->next->score[1] = pr->score[1]; p->next->score[2] = pr->score[2]; } p = p->next; } p = now->next; now = now->next; } }
时间: 2023-08-07 15:02:44 浏览: 114
STU417S-VB一种P沟道TO252封装MOS管
你提供的`Sort`函数实现了一个简单的冒泡排序算法来按照学生总分从高到低对链表进行排序。代码中使用了结构体成员变量之间的赋值和字符串拷贝操作。
但是你的代码存在一个问题,就是在内层循环中,你没有更新`pr`指针。这会导致每次交换后,`pr`指针都保持不变,而应该向前移动一个位置。
以下是修复这个问题的修改后的代码:
```c
void Sort(STU *head) {
STU *p, *now, *pr;
p = head->next;
now = head;
pr = head;
while (p != NULL) {
while (p->next != NULL) {
if ((p->score[0] + p->score[1] + p->score[2]) < (p->next->score[0] + p->next->score[1] + p->next->score[2])) {
strcpy(pr->num, p->num);
strcpy(pr->name, p->name);
strcpy(pr->major, p->major);
pr->classNo = p->classNo;
pr->score[0] = p->score[0];
pr->score[1] = p->score[1];
pr->score[2] = p->score[2];
strcpy(p->num, p->next->num);
strcpy(p->name, p->next->name);
strcpy(p->major, p->next->major);
p->classNo = p->next->classNo;
p->score[0] = p->next->score[0];
p->score[1] = p->next->score[1];
p->score[2] = p->next->score[2];
strcpy(p->next->num, pr->num);
strcpy(p->next->name, pr->name);
strcpy(p->next->major, pr->major);
p->next->classNo = pr->classNo;
p->next->score[0] = pr->score[0];
p->next->score[1] = pr->score[1];
p->next->score[2] = pr->score[2];
}
p = p->next;
pr = pr->next; // 添加这一行来更新pr指针
}
p = now->next;
now = now->next;
}
}
```
这样,`pr`指针在内层循环中会向前移动一个位置,确保下一次交换时指向正确的位置。
请记得在调用`Sort`函数时传入合适的参数。
阅读全文