C语言在学生信息单链表中查找指定姓名的学生成绩,并打印出姓名,成绩
时间: 2023-12-31 17:05:19 浏览: 78
以下是一个示例代码,实现了在学生信息单链表中查找指定姓名的学生成绩,并打印出姓名和成绩:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char name[20];
int score;
struct Student *next;
};
struct Student *create_student(char *name, int score) {
struct Student *s = (struct Student *)malloc(sizeof(struct Student));
strcpy(s->name, name);
s->score = score;
s->next = NULL;
return s;
}
void insert_student(struct Student **head, struct Student *s) {
if (*head == NULL) {
*head = s;
} else {
struct Student *p = *head;
while (p->next != NULL) {
p = p->next;
}
p->next = s;
}
}
void print_student(struct Student *s) {
printf("%s: %d\n", s->name, s->score);
}
struct Student *find_student(struct Student *head, char *name) {
struct Student *p = head;
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
int main() {
struct Student *head = NULL;
insert_student(&head, create_student("Alice", 90));
insert_student(&head, create_student("Bob", 80));
insert_student(&head, create_student("Charlie", 70));
insert_student(&head, create_student("David", 60));
char name[20];
printf("Enter a name to search: ");
scanf("%s", name);
struct Student *s = find_student(head, name);
if (s != NULL) {
print_student(s);
} else {
printf("No such student.\n");
}
return 0;
}
```
在这个示例代码中,我们定义了一个 `Student` 结构体表示学生的信息,包括姓名和成绩。我们使用单链表来存储多个学生的信息,使用 `create_student` 函数来创建一个新的学生节点,使用 `insert_student` 函数来插入一个学生节点到链表中,使用 `print_student` 函数来打印一个学生的信息。
在 `find_student` 函数中,我们使用一个指针 `p` 来遍历整个链表,查找与指定姓名匹配的学生节点。如果找到了,就返回该节点的指针;如果遍历完整个链表都没有找到,就返回 `NULL`。最后,在 `main` 函数中,我们输入一个要查找的姓名,调用 `find_student` 函数来查找该学生的信息,如果找到了就打印出来,否则输出一条提示信息。