酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

C语言实现单链表学生信息存储、插入、排序与逆序操作

#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; } ######[AI写代码神器 | 1695点数解答 | 2024-07-21 10:59:56]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]