【发布时间】:2021-02-17 03:43:27
【问题描述】:
我想按照分数从高到低对我在 Main 方法中添加的学生的索引进行排序。这是我要创建的列表的最后一种形式。
0,18061086,65
1,20060032,60
2,20060678,55
3,20060045,50
4,19061091,45
5,18060311,40
6,20060134,30
这是我写的代码:
#include<stdio.h>
#include<stdlib.h>
struct student{
int index;
int studentnumber;
int score;
struct student* next;
};
typedef struct student Student;
void addStudent(Student **headOfList,int index,int studentnumber,int score);
void score(Student* headOfList);
int main(){
Student* headOfList = NULL;
addStudent(&headOfList,0,18060311,40);
addStudent(&headOfList,1,20060045,50);
addStudent(&headOfList,2,19061091,45);
addStudent(&headOfList,3,20060134,30);
addStudent(&headOfList,4,20060678,55);
addStudent(&headOfList,5,18061086,65);
addStudent(&headOfList,6,20060032,60);
return 0;
}
void addStudent(Student **headOfList,int index,int studentnumber,int score){
Student* currentStudent = (*headOfList);
Student* newStudent = (Student*)malloc(sizeof(Student));
newStudent->index =index;
newStudent->studentnumber = studentnumber;
newStudent->score = score;
newStudent->next = NULL;
if(currentStudent == NULL){
// if list is empty
(*headOfList)= newStudent;
}
else{
while(currentStudent->next != NULL){
currentStudent = currentStudent->next;
}
currentStudent -> next = newStudent;
}
}
【问题讨论】:
-
如果您在 head 中跟踪学生总数,那么您可以创建一个中间预分配的指向列表元素的指针数组。使用这个指针列表,您可以将自己的比较器连接到 stdlib qsort 函数。当指针列表根据您的比较器进行排序时,您可以遍历您的列表,从第二个开始一个接一个地更新下一个指针,最后将头部中的下一个指针更新为排序列表中的第一个指针。
标签: c pointers data-structures linked-list structure