用c语言以链表形式写一个学生管理系统,要求可以增、删、改、查学生程序
时间: 2023-05-20 15:05:15 浏览: 47
非常好的问题!以下是一个简单的学生管理系统的C语言链表实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
int id;
char name[50];
int age;
struct student *next;
};
struct student *head = NULL;
void add_student(int id, char *name, int age) {
struct student *new_student = (struct student*) malloc(sizeof(struct student));
new_student->id = id;
strcpy(new_student->name, name);
new_student->age = age;
new_student->next = NULL;
if (head == NULL) {
head = new_student;
} else {
struct student *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_student;
}
}
void delete_student(int id) {
struct student *current = head;
struct student *previous = NULL;
while (current != NULL && current->id != id) {
previous = current;
current = current->next;
}
if (current == NULL) {
printf("Student with ID %d not found\n", id);
return;
}
if (previous == NULL) {
head = current->next;
} else {
previous->next = current->next;
}
free(current);
}
void update_student(int id, char *name, int age) {
struct student *current = head;
while (current != NULL && current->id != id) {
current = current->next;
}
if (current == NULL) {
printf("Student with ID %d not found\n", id);
return;
}
strcpy(current->name, name);
current->age = age;
}
void print_student(int id) {
struct student *current = head;
while (current != NULL && current->id != id) {
current = current->next;
}
if (current == NULL) {
printf("Student with ID %d not found\n", id);
return;
}
printf("ID: %d\n", current->id);
printf("Name: %s\n", current->name);
printf("Age: %d\n", current->age);
}
void print_all_students() {
struct student *current = head;
while (current != NULL) {
printf("ID: %d\n", current->id);
printf("Name: %s\n", current->name);
printf("Age: %d\n", current->age);
printf("\n");
current = current->next;
}
}
int main() {
add_student(1, "Alice", 20);
add_student(2, "Bob", 21);
add_student(3, "Charlie", 22);
print_all_students();
delete_student(2);
print_all_students();
update_student(3, "David", 23);
print_student(3);
return 0;
}
```
这个程序使用了一个结构体来表示学生,包含学生的ID、姓名和年龄,以及一个指向下一个学生的指针。我们可以使用`add_student`函数来添加学生,使用`delete_student`函数来删除学生,使用`update_student`函数来更新学生的信息,使用`print_student`函数来打印单个学生的信息,使用`print_all_students`函数来打印所有学生的信息。
希望这个程序能够帮助你理解如何使用链表来实现一个简单的学生管理系统!