#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Student { int id; char name[20]; int score; struct Student* next; } Student; // 创建带头节点的单链表 Student* createLinkedList() { Student* head = (Student*)malloc(sizeof(Student)); head->next = NULL; return head; } // 在单链表中插入学生信息 void insertStudent(Student* head, int id, char* name, int score) { Student* newStudent = (Student*)malloc(sizeof(Student)); newStudent->id = id; strcpy(newStudent->name, name); newStudent->score = score; Student* p = head; while (p->next != NULL) { p = p->next; } p->next = newStudent; newStudent->next = NULL; } // 对学生信息进行排序,按照分数从小到大的顺序进行排序 void sortStudents(Student* head) { Student *p, *q; int temp; char tempName[20]; for(p = head->next; p != NULL; p = p->next) { for(q = p->next; q != NULL; q = q->next) { if(p->score > q->score) { temp = p->score; p->score = q->score; q->score = temp; strcpy(tempName, p->name); strcpy(p->name, q->name); strcpy(q->name, tempName); } } } } // 对学生信息进行逆序操作,让学生分数从大到小存储在单链表中 void reverseStudents(Student* head) { Student* prev = NULL; Student* current = head->next; Student* next = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } head->next = prev; } // 输出学生信息 void printStudents(Student* head) { Student* p = head->next; while (p != NULL) { printf("学号: %d, 姓名: %s, 分数: %d\n", p->id, p->name, p->score); p = p->next; } } int main() { Student* head = createLinkedList(); // 初始数据 insertStudent(head, 1, "王令", 98); insertStudent(head, 3, "张成", 67); insertStudent(head, 5, "陈晨", 74); insertStudent(head, 7, "王家", 82); insertStudent(head, 2, "张都", 68); insertStudent(head, 9, "万洪", 73); // 插入新数据 insertStudent(head, 12, "林嘉", 84); printf("排序前:\n"); printStudents(head); sortStudents(head); printf("\n分数从小到大排序后:\n"); printStudents(head); reverseStudents(head); printf("\n分数从大到小排序后:\n"); printStudents(head); return 0; } [2024-07-21 10:59:56 | AI写代码神器 | 1695点数解答]