C语言实现单链表管理学生信息,程序实现了以下功能:
- 添加学生信息到链表末尾。
- 删除指定学号的学生信息。
- 查找指定学号的学生信息。
- 修改指定学号的学生信息。
- 打印链表中所有学生信息。
程序通过结构体 Student
存储每个学生的学号、姓名和成绩,并使用单链表将学生信息连接起来。每个节点表示一个学生,包含学生信息和指向下一个节点的指针。通过调用不同的函数来实现不同的操作,如添加、删除、查找和修改学生信息。最后,主函数演示了如何使用这些功能来管理学生信息。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
struct Student {
int roll_no;
char name[50];
float marks;
struct Student* next;
};
// 在链表末尾添加学生信息
void append(struct Student** head_ref, int roll_no, char* name, float marks) {
// 分配新节点内存空间
struct Student* new_student = (struct Student*)malloc(sizeof(struct Student));
if (new_student == NULL) {
// 内存分配失败,处理错误
printf("内存分配失败\n");
return;
}
struct Student* last = *head_ref; // 用于遍历链表找到末尾节点
// 设置新节点的数据
new_student->roll_no = roll_no;
strcpy_s(new_student->name, sizeof(new_student->name), name);
new_student->marks = marks;
new_student->next = NULL;
// 如果链表为空,则将新节点作为头节点
if (*head_ref == NULL) {
*head_ref = new_student;
return;
}
// 否则遍历链表找到末尾节点
while (last->next != NULL) {
last = last->next;
}
// 将新节点链接到末尾节点
last->next = new_student;
}
// 删除指定学号的学生信息
void deleteStudent(struct Student** head_ref, int roll_no) {
struct Student* temp = *head_ref;
struct Student* prev = NULL;
// 如果第一个节点就是要删除的节点
if (temp != NULL && temp->roll_no == roll_no) {
*head_ref = temp->next;
free(temp);
return;
}
// 查找要删除的节点,并记录其前一个节点
while (temp != NULL && temp->roll_no != roll_no) {
prev = temp;
temp = temp->next;
}
// 如果找到要删除的节点
if (temp == NULL) {
printf("未找到学号为 %d 的学生信息。\n", roll_no);
return;
}
// 将要删除的节点从链表中移除
prev->next = temp->next;
free(temp);
}
// 查找指定学号的学生信息
void findStudent(struct Student* head, int roll_no) {
while (head != NULL) {
if (head->roll_no == roll_no) {
printf("学号:%d,姓名:%s,成绩:%.2f\n", head->roll_no, head->name, head->marks);
return;
}
head = head->next;
}
printf("未找到学号为 %d 的学生信息。\n", roll_no);
}
// 修改指定学号的学生信息
void modifyStudent(struct Student* head, int roll_no, char* new_name, float new_marks) {
while (head != NULL) {
if (head->roll_no == roll_no) {
strcpy_s(head->name, sizeof(new_name), new_name);
head->marks = new_marks;
return;
}
head = head->next;
}
printf("未找到学号为 %d 的学生信息。\n", roll_no);
}
// 打印链表中所有学生信息
void printStudents(struct Student* head) {
while (head != NULL) {
printf("学号:%d,姓名:%s,成绩:%.2f\n", head->roll_no, head->name, head->marks);
head = head->next;
}
}
// 主函数
int main() {
// 初始化链表为空
struct Student* head = NULL;
// 添加几个学生信息到链表末尾
append(&head, 1, "John", 85.5);
append(&head, 2, "Alice", 90.0);
append(&head, 3, "Bob", 78.5);
append(&head, 4, "Emma", 95.2);
// 打印链表中所有学生信息
printf("学生信息如下:\n");
printStudents(head);
// 删除学号为3的学生信息
deleteStudent(&head, 3);
printf("\n删除学号为 3 的学生信息后:\n");
printStudents(head);
// 查找学号为2的学生信息
printf("\n学号为 2 的学生信息:\n");
findStudent(head, 2);
// 修改学号为1的学生信息
printf("\n修改学号为 1 的学生信息后:\n");
modifyStudent(head, 1, "David", 88.0);
printStudents(head);
return 0;
}