链表写学生信息管理系统
时间: 2023-12-15 13:30:56 浏览: 31
链表可以用于实现学生信息管理系统,以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct student {
int id; // 学号
char name[20]; // 姓名
int age; // 年龄
struct student *next; // 指向下一个学生的指针
} Student;
// 添加学生信息
void addStudent(Student **head, int id, char *name, int age) {
Student *newStudent = (Student *)malloc(sizeof(Student));
newStudent->id = id;
strcpy(newStudent->name, name);
newStudent->age = age;
newStudent->next = NULL;
if (*head == NULL) {
*head = newStudent;
} else {
Student *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newStudent;
}
}
// 删除学生信息
void deleteStudent(Student **head, int id) {
if (*head == NULL) {
printf("链表为空,无法删除!\n");
return;
}
Student *temp = *head;
Student *prev = NULL;
while (temp != NULL) {
if (temp->id == id) {
if (prev == NULL) {
*head = temp->next;
} else {
prev->next = temp->next;
}
free(temp);
printf("删除成功!\n");
return;
}
prev = temp;
temp = temp->next;
}
printf("未找到该学生信息!\n");
}
// 修改学生信息
void modifyStudent(Student *head, int id, char *name, int age) {
if (head == NULL) {
printf("链表为空,无法修改!\n");
return;
}
Student *temp = head;
while (temp != NULL) {
if (temp->id == id) {
strcpy(temp->name, name);
temp->age = age;
printf("修改成功!\n");
return;
}
temp = temp->next;
}
printf("未找到该学生信息!\n");
}
// 查找学生信息
void findStudent(Student *head, int id) {
if (head == NULL) {
printf("链表为空,无法查找!\n");
return;
}
Student *temp = head;
while (temp != NULL) {
if (temp->id == id) {
printf("学号:%d,姓名:%s,年龄:%d\n", temp->id, temp->name, temp->age);
return;
}
temp = temp->next;
}
printf("未找到该学生信息!\n");
}
// 显示所有学生信息
void showAllStudents(Student *head) {
if (head == NULL) {
printf("链表为空,无法显示!\n");
return;
}
Student *temp = head;
while (temp != NULL) {
printf("学号:%d,姓名:%s,年龄:%d\n", temp->id, temp->name, temp->age);
temp = temp->next;
}
}
// 释放链表内存
void freeList(Student **head) {
Student *temp = *head;
while (temp != NULL) {
*head = temp->next;
free(temp);
temp = *head;
}
}
int main() {
Student *head = NULL;
int choice, id, age;
char name[20];
while (1) {
printf("请选择操作:\n");
printf("1.添加学生信息\n");
printf("2.删除学生信息\n");
printf("3.修改学生信息\n");
printf("4.查找学生信息\n");
printf("5.显示所有学生信息\n");
printf("6.退出程序\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入学号、姓名、年龄:\n");
scanf("%d %s %d", &id, name, &age);
addStudent(&head, id, name, age);
break;
case 2:
printf("请输入要删除的学生学号:\n");
scanf("%d", &id);
deleteStudent(&head, id);
break;
case 3:
printf("请输入要修改的学生学号、姓名、年龄:\n");
scanf("%d %s %d", &id, name, &age);
modifyStudent(head, id, name, age);
break;
case 4:
printf("请输入要查找的学生学号:\n");
scanf("%d", &id);
findStudent(head, id);
break;
case 5:
showAllStudents(head);
break;
case 6:
freeList(&head);
exit(0);
default:
printf("输入有误,请重新输入!\n");
break;
}
}
return 0;
}
```