c语言链表实现学生管理系统
时间: 2024-11-20 07:41:53 浏览: 14
在C语言中,实现一个简单的学生管理系统通常会涉及到结构体、链表数据结构以及一些基本操作函数如插入、删除、查找等。首先,我们定义一个`Student`结构体,包含学生的姓名和学号:
```c
typedef struct {
char name[50];
int id;
} Student;
```
接着,创建一个单向链表节点,用于存储学生信息:
```c
typedef struct Node {
Student student;
struct Node* next;
} Node;
```
然后,我们可以编写以下关键函数来管理链表:
1. **初始化链表**:
```c
void initList(Node** head) {
*head = NULL;
}
```
2. **添加新学生**:
```c
void addStudent(Node** head, const char* name, int id) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
strcpy(newNode->student.name, name);
newNode->student.id = id;
newNode->next = *head;
*head = newNode;
} else {
printf("Memory allocation failed.\n");
}
}
```
3. **查找学生**:
```c
bool searchStudent(Node* head, const char* name, int id) {
while (head != NULL) {
if (strcmp(head->student.name, name) == 0 && head->student.id == id) {
return true;
}
head = head->next;
}
return false;
}
```
4. **删除学生**:
```c
void deleteStudent(Node** head, const char* name, int id) {
Node* current = *head;
Node* prev = NULL;
if (current != NULL && strcmp(current->student.name, name) == 0 && current->student.id == id) {
*head = current->next;
free(current);
return;
}
while (current != NULL && strcmp(current->student.name, name) != 0 && current->student.id != id) {
prev = current;
current = current->next;
}
if (current != NULL) {
prev->next = current->next;
free(current);
} else {
printf("Student not found.\n");
}
}
```
最后,为了展示链表的操作,你可以提供一个主函数来处理用户输入:
```c
int main() {
Node* head = NULL;
// 初始化链表
initList(&head);
// 添加、查找和删除学生示例
// ...
return 0;
}
```
阅读全文