为了实现这个程序,我们需要定义学生信息的结构体,并实现链表的创建、插入、删除、修改、查找和显示功能。以下是一个用C语言编写的示例: ```c #include #include #include // 定义学生信息结构体 typedef struct Student { int id; char sex; int age; char class[31]; // 班级信息,额外加一个字符位置存放字符串结尾符'\0' struct Student *next; } Student; // 函数声明 Student* createStudentList(int num); void insertStudent(Student **head, int id, char sex, int age, char *class); void deleteStudent(Student **head, int id); void updateStudent(Student **head, int id, char sex, int age, char *class); void findStudent(Student *head, int id); void displayStudents(Student *head); void freeStudentList(Student *head); int main() { int num; printf("请输入班级的学生人数: "); scanf("%d", &num); Student *head = NULL; head = createStudentList(num); displayStudents(head); // 这里可以添加代码来测试其他功能,比如插入、删除、修改、查找等 freeStudentList(head); return 0; } // 学生信息的初始化(链表的创建) Student* createStudentList(int num) { Student *head = NULL, *tail = NULL, *newNode; for (int i = 0; i < num; ++i) { newNode = (Student*)malloc(sizeof(Student)); printf("请输入第%d个学生的学号: ", i + 1); scanf("%d", &newNode->id); printf("请输入第%d个学生的性别: ", i + 1); scanf(" %c", &newNode->sex); printf("请输入第%d个学生的年龄: ", i + 1); scanf("%d", &newNode->age); printf("请输入第%d个学生所在的班级: ", i + 1); scanf(" %s", newNode->class); newNode->next = NULL; if (head == NULL) { head = newNode; } else { tail->next = newNode; } tail = newNode; } return head; } // 学生的插入 void insertStudent(Student **head, int id, char sex, int age, char *class) { Student *newNode = (Student*)malloc(sizeof(Student)); newNode->id = id; newNode->sex = sex; newNode->age = age; strcpy(newNode->class, class); newNode->next = *head; *head = newNode; } // 学生的删除(按学号删除) void deleteStudent(Student **head, int id) { Student *current = *head; Student *prev = NULL; while (current != NULL && current->id != id) { prev = current; current = current->next; } if (current == NULL) { printf("没有找到学号为%d的学生\n", id); } else { if (prev == NULL) { *head = current->next; } else { prev->next = current->next; } free(current); printf("学号为%d的学生已被删除\n", id); } } // 学生信息的修改(按学号查找到该学生并修改) void updateStudent(Student **head, int id, char sex, int age, char *class) { Student *current = *head; while (current != NULL && current->id != id) { current = current->next; } if (current == NULL) { printf("没有找到学号为%d的学生\n", id); } else { current->sex = sex; current->age = age; strcpy(current->class, class); printf("学号为%d的学生信息已更新\n", id); } } // 学生信息的查找(按学号查找) void findStudent(Student *head, int id) { Student *current = head; while (current != NULL) { if (current->id

点赞(0)
×
关注公众号,登录后继续创作
或点击进入高级版AI
扫码关注后未收到验证码,回复【登录】二字获取验证码
发表
评论
返回
顶部