用带有头节点的单链表实现学生管理系统,功能包括录入学生学号,姓名,成绩(int 类型),插入新学生,删除学生,删除成绩为x的学生,c语言
时间: 2024-10-19 18:10:27 浏览: 33
单链表学生成绩管理系统
在C语言中,我们可以使用结构体(struct)来表示学生信息,并结合链表数据结构来实现一个简单的学生管理系统。首先,定义一个包含学生信息的链表节点:
```c
typedef struct StudentNode {
int studentID; // 学生学号
char name[50]; // 学生姓名
int score; // 成绩
struct StudentNode* next; // 指向下一个节点的指针
} StudentNode;
```
接下来,创建链表头部指针head,初始化为空:
```c
StudentNode* head = NULL;
```
然后我们实现相应功能:
1. **录入学生**(addStudent):
- 创建一个新的节点,存储输入的数据
- 将新节点设置为head并链接到当前链表
```c
void addStudent(int id, const char* name, int score) {
StudentNode* newNode = (StudentNode*)malloc(sizeof(StudentNode));
newNode->studentID = id;
strcpy(newNode->name, name);
newNode->score = score;
newNode->next = head;
head = newNode;
}
```
2. **删除学生**(deleteStudentByID):
- 遍历链表查找指定ID的学生,如果找到则删除它
```c
void deleteStudentByID(int id) {
if (head == NULL) return;
StudentNode* curr = head;
while (curr != NULL) {
if (curr->studentID == id) {
if (curr == head) {
head = curr->next;
} else {
StudentNode* prev = curr->prev;
prev->next = curr->next;
}
free(curr);
break;
}
curr = curr->next;
}
}
```
3. **删除成绩为x的学生**(deleteStudentsByScore):
- 同样遍历链表,找出所有分数为x的学生并删除
```c
void deleteStudentsByScore(int x) {
if (head == NULL) return;
StudentNode* curr = head;
while (curr != NULL) {
if (curr->score == x) {
if (curr == head) {
head = curr->next;
free(curr);
} else {
StudentNode* prev = curr->prev;
prev->next = curr->next;
free(curr);
}
} else {
curr = curr->next;
}
}
}
```
4. **显示所有学生**(displayStudents):
- 遍历整个链表并打印学生信息
```c
void displayStudents() {
if (head == NULL) return;
StudentNode* curr = head;
while (curr != NULL) {
printf("学号:%d 姓名:%s 分数:%d\n", curr->studentID, curr->name, curr->score);
curr = curr->next;
}
}
```
阅读全文