要解决这个问题,首先需要定义一个结构体来存储学生信息,然后使用单链表来存储这些信息。接下来,根据你的需求,我们将逐步实现每个功能。 1. 定义学生结构体和链表节点 ```c #include <stdio.h> #include <stdlib.h> typedef struct Student { int id; char name[20]; int score; struct Student *next; } Student; // 创建一个新的学生节点 Student* createStudent(int id, const char *name, int score) { Student *newStudent = (Student*)malloc(sizeof(Student)); newStudent->id = id; strcpy(newStudent->name, name); newStudent->score = score; newStudent->next = NULL; return newStudent; } ``` 2. 建立单链表并插入初始学生信息 ```c void insertAtEnd(Student head, int id, const char *name, int score) { Student *newNode = createStudent(id, name, score); if (*head == NULL) { *head = newNode; return; } Student *last = *head; while (last->next != NULL) { last = last->next; } last->next = newNode; } int main() { Student *head = NULL; insertAtEnd(&head, 1, "王令", 98); insertAtEnd(&head, 3, "张成", 67); insertAtEnd(&head, 5, "陈晨", 74); insertAtEnd(&head, 7, "王家", 82); insertAtEnd(&head, 2, "张都", 68); insertAtEnd(&head, 9, "万洪", 73); } ``` 3. 插入新学生信息 ```c void insertNewStudent(Student head, int id, const char *name, int score) { insertAtEnd(head, id, name, score); } // 在主函数中调用 insertNewStudent(&head, 12, "林嘉", 84); ``` 4. 排序并输出 小到大排序 ```c void sortList(Student head) { Student *current = *head; Student *index = NULL; int tempScore; char tempName[20]; int tempId; if (head == NULL) { return; } else { while (current != NULL) { index = current->next; while (index != NULL) { if (current->score > index->score) { tempScore = current->score; current->score = index->score; index->score = tempScore; tempId = current->id; current->id = index->id; index->id = tempId; strcpy(tempName, current->name); strcpy(current->name, index->name); strcpy(index->name, tempName); } index = index->next; } current = current->next; } } } void printList(Student *head) { while (head != NULL) { printf("ID: %d, Name: %s, Score: %d\n", head->id, head->name, head->score); head = head->next; } } ``` 大到小排序 只需在`sortList`函数中的比较条件改为`current->score < index->score`即可。 完整代码 将以上所有部分组合起来,你就可以得到完整的程序。注意在实际使用中,你需要在`main`函数中调用所有这些函数,并且在程序结束时释放所有分配的内存以避免内存泄漏。 [2024-07-21 10:54:07 | AI写代码神器 | 828点数解答]