现有学生结构体( id, name, score),写代码实现 (1) 以该结构体为基础, 创建一个链表, 并初始化头节点 (2) 添加学员, 要求 id自增 (3) 删除指定姓名的学生 (4分: 头节点初始化1分, 添加学生1.5分, 删除学生1.5分)
时间: 2024-12-19 12:22:01 浏览: 7
首先,我们需要定义一个包含学生ID、名字和分数的结构体,以及链表节点的结构。这里假设我们已经有一个名为`Student`的结构体,然后我们将创建一个`ListNode`结构来代表链表节点:
```c
typedef struct ListNode {
Student student;
struct ListNode* next;
} ListNode;
typedef struct Student {
int id;
char name[50];
float score;
} Student;
```
接着,我们可以实现链表相关的功能:
1. 初始化头节点:
```c
ListNode* createHeadNode() {
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
if (!head) {
printf("Memory allocation failed.\n");
return NULL;
}
head->student.id = 0; // 自增id在这里通常是错误的,因为这应该在添加新节点时完成
head->student.name[0] = '\0';
head->student.score = 0.0;
head->next = NULL;
return head;
}
// 示例:创建并初始化头节点
ListNode* head = createHeadNode();
```
2. 添加学员(自增id):
```c
void addStudentToList(ListNode** head, const char* name, float score) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
// 检查是否需要自增id,这里假设id存储在头节点,实际应用中可能需要数据库操作
if (*head == NULL || ((*head)->student.id != 0 && (*head)->student.id > newNode->student.id)) {
newNode->student.id = (*head)->student.id + 1;
} else {
newNode->student.id = 1;
}
strncpy(newNode->student.name, name, sizeof(newNode->student.name));
newNode->student.score = score;
newNode->next = *head;
*head = newNode;
}
```
3. 删除指定姓名的学生:
```c
void removeStudentByName(ListNode** head, const char* name) {
if (*head == NULL) {
return;
}
ListNode* current = *head;
ListNode* prev = NULL;
while (current != NULL && strcmp(current->student.name, name) != 0) {
prev = current;
current = current->next;
}
if (current == NULL) {
printf("Student not found.\n");
return;
}
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
}
```
阅读全文