用c语言编写完整代码定义一个包含学生信息(学号,姓名,成绩)的链表,使其具有如下功能: (1) 输入学生信息; (2) 显示学生表中所有学生的相关信息; (3) 根据姓名进行查找,返回此学生的学号和成绩; (4) 根据指
时间: 2024-10-16 17:12:59 浏览: 152
在C语言中,我们可以使用结构体、链表以及函数来实现这个功能。首先,我们需要定义一个`Student`结构体存储学生的信息,然后创建一个单向链表来存储学生列表。下面是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct {
int id;
char name[50];
float score;
} Student;
// 创建链表节点
typedef struct Node {
Student student;
struct Node* next;
} Node;
// 链表头结点
Node* head = NULL;
// 添加新学生到链表
void addStudent(int id, char* name, float score) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
strcpy(newNode->student.name, name);
newNode->student.id = id;
newNode->student.score = score;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 显示链表中的所有学生信息
void displayStudents() {
if (head == NULL) {
printf("No students in the list.\n");
return;
}
Node* current = head;
while (current != NULL) {
printf("ID: %d, Name: %s, Score: %.2f\n", current->student.id, current->student.name, current->student.score);
current = current->next;
}
}
// 搜索学生并返回相关信息
void searchByName(char* name) {
if (head == NULL) {
printf("No students found with that name.\n");
return;
}
Node* current = head;
while (current != NULL) {
if (strcmp(current->student.name, name) == 0) {
printf("Found student with ID: %d and Score: %.2f\n", current->student.id, current->student.score);
break;
}
current = current->next;
}
}
int main() {
// 示例输入
int id, score;
char name[50];
printf("Enter student details:\n");
scanf("%d %s %f", &id, name, &score);
// 添加学生
addStudent(id, name, score);
// 显示所有学生
displayStudents();
// 搜索学生
char searchName[50];
printf("Search a student by name: ");
scanf("%s", searchName);
searchByName(searchName);
return 0;
}
```
阅读全文