c语言课程设计链表实现学生信息管理系统
时间: 2023-10-10 07:04:51 浏览: 160
很高兴回答你关于C语言课程设计的问题!链表是一种常用的数据结构,可以用来实现学生信息管理系统。下面是一个简单的示例代码,实现了学生信息的添加、查找和删除功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char name[50];
int age;
struct student* next;
} Student;
Student* createStudent(char name[], int age) {
Student* newStudent = (Student*)malloc(sizeof(Student));
strcpy(newStudent->name, name);
newStudent->age = age;
newStudent->next = NULL;
return newStudent;
}
void addStudent(Student** head, char name[], int age) {
Student* newStudent = createStudent(name, age);
if (*head == NULL) {
*head = newStudent;
} else {
Student* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newStudent;
}
printf("学生 %s 添加成功\n", name);
}
void findStudent(Student* head, char name[]) {
if (head == NULL) {
printf("学生信息为空\n");
return;
}
Student* temp = head;
while (temp != NULL) {
if (strcmp(temp->name, name) == 0) {
printf("找到学生 %s,年龄:%d\n", name, temp->age);
return;
}
temp = temp->next;
}
printf("未找到学生 %s\n", name);
}
void deleteStudent(Student** head, char name[]) {
if (*head == NULL) {
printf("学生信息为空\n");
return;
}
Student* temp = *head;
Student* prev = NULL;
while (temp != NULL) {
if (strcmp(temp->name, name) == 0) {
if (prev == NULL) {
*head = temp->next; } else {
prev->next = temp->next;
}
free(temp);
printf("删除学生 %s 成功\n", name);
return;
}
prev = temp;
temp = temp->next;
}
printf("未找到学生 %s\n", name);
}
void printStudents(Student* head) {
if (head == NULL) {
printf("学生信息为空\n");
return;
}
printf("学生信息列表:\n");
Student* temp = head;
while (temp != NULL) {
printf("姓名:%s,年龄:%d\n", temp->name, temp->age);
temp = temp->next;
}
}
void destroyStudents(Student** head) {
if (*head == NULL) {
return;
}
Student* current = *head;
Student* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*head = NULL;
printf("释放学生信息成功\n");
}
int main() {
Student* head = NULL;
addStudent(&head, "张三", 20);
addStudent(&head, "李四", 21);
addStudent(&head, "王五", 22);
printStudents(head);
findStudent(head, "李四");
findStudent(head, "赵六");
deleteStudent(&head, "李四");
printStudents(head);
destroyStudents(&head);
return 0;
}
```
这个例子中,我们定义了一个`Student`结构体,包含学生的姓名和年龄,并且有一个指向下一个学生的指针。我们可以使用`createStudent`函数创建一个新的学生节点,然后用`addStudent`函数将学生添加到链表中。`findStudent`函数用于查找指定姓名的学生,`deleteStudent`函数用于删除指定姓名的学生,`printStudents`函数用于打印所有学生信息,`destroyStudents`函数用于释放链表内存。
希望这个示例能够帮助你开始实现学生信息管理系统!如果你有任何问题,请随时提问。
阅读全文