帮我写一个满足单链表所有基本操作的C语言代码,用来统计学生的成绩
时间: 2023-05-30 18:02:43 浏览: 108
#include <stdio.h>
#include <stdlib.h>
// 学生结构体
typedef struct Student {
int id; // 学号
char name[20]; // 姓名
float score; // 成绩
struct Student *next; // 下一个节点的指针
} Student;
// 创建一个新的学生节点
Student *createStudent(int id, char *name, float score) {
Student *newStudent = (Student*)malloc(sizeof(Student));
newStudent->id = id;
strcpy(newStudent->name, name);
newStudent->score = score;
newStudent->next = NULL;
return newStudent;
}
// 在链表的末尾添加一个学生
void addStudent(Student **head, Student *newStudent) {
if (*head == NULL) {
*head = newStudent;
return;
}
Student *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
// 在链表中查找一个学生
Student *findStudent(Student *head, int id) {
Student *current = head;
while (current != NULL) {
if (current->id == id) {
return current;
}
current = current->next;
}
return NULL;
}
// 在链表中删除一个学生
void deleteStudent(Student **head, int id) {
Student *current = *head;
Student *previous = NULL;
while (current != NULL) {
if (current->id == id) {
if (previous == NULL) {
*head = current->next;
} else {
previous->next = current->next;
}
free(current);
return;
}
previous = current;
current = current->next;
}
}
// 修改一个学生的信息
void modifyStudent(Student *student, char *name, float score) {
strcpy(student->name, name);
student->score = score;
}
// 输出链表中所有学生的信息
void printStudents(Student *head) {
printf("学号\t姓名\t成绩\n");
Student *current = head;
while (current != NULL) {
printf("%d\t%s\t%.1f\n", current->id, current->name, current->score);
current = current->next;
}
}
int main() {
Student *head = NULL;
// 添加学生
addStudent(&head, createStudent(1001, "张三", 80.5));
addStudent(&head, createStudent(1002, "李四", 75.0));
addStudent(&head, createStudent(1003, "王五", 90.0));
// 输出所有学生的信息
printStudents(head);
// 查找学生
printf("查找学生1002:\n");
Student *student = findStudent(head, 1002);
if (student == NULL) {
printf("没有找到该学生!\n");
} else {
printf("学号:%d\n姓名:%s\n成绩:%.1f\n", student->id, student->name, student->score);
}
// 修改学生信息
printf("修改学生1003的信息为:\n");
modifyStudent(findStudent(head, 1003), "赵六", 85.0);
printStudents(head);
// 删除学生
printf("删除学生1002:\n");
deleteStudent(&head, 1002);
printStudents(head);
return 0;
}
阅读全文