用C语言已知5个学生的信息存储在一个链表中,编写函数实现数据的删除:从已有链表中删除一个学生(根据学生的姓名删除)。在main函数中输出删除后的结果。
时间: 2023-06-07 17:10:19 浏览: 84
C语言链表实现学生信息管理
好的,我理解了你的要求。以下是答案:
首先,我们需要定义结构体存储学生信息:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[20];
int age;
char sex;
struct student *next;
};
```
然后,我们需要编写函数实现数据的删除:
```c
struct student *delete_node(struct student *head, char *name) {
struct student *p = head;
struct student *prev = head;
if (strcmp(p->name, name) == 0) {
head = head->next;
free(p);
printf("Delete student %s\n", name);
return head;
}
while (p != NULL) {
if (strcmp(p->name, name) == 0) {
prev->next = p->next;
free(p);
printf("Delete student %s\n", name);
return head;
}
prev = p;
p = p->next;
}
printf("Student %s not found\n", name);
return head;
}
```
在 main 函数中,我们可以创建一个包含 5 个学生信息的链表,并调用 delete_node 函数删除指定的学生信息:
```c
int main() {
struct student *head = NULL;
struct student *p, *q;
p = (struct student *)malloc(sizeof(struct student));
strcpy(p->name, "Tom");
p->age = 18;
p->sex = 'M';
head = p;
q = (struct student *)malloc(sizeof(struct student));
strcpy(q->name, "Amy");
q->age = 17;
q->sex = 'F';
p->next = q;
p = q;
q = (struct student *)malloc(sizeof(struct student));
strcpy(q->name, "Jack");
q->age = 19;
q->sex = 'M';
p->next = q;
p = q;
q = (struct student *)malloc(sizeof(struct student));
strcpy(q->name, "Lucy");
q->age = 18;
q->sex = 'F';
p->next = q;
p = q;
q = (struct student *)malloc(sizeof(struct student));
strcpy(q->name, "David");
q->age = 20;
q->sex = 'M';
p->next = q;
p = q;
q->next = NULL;
head = delete_node(head, "Lucy"); // 删除名为 Lucy 的学生
head = delete_node(head, "Rose"); // 删除名为 Rose 的学生(不存在)
p = head;
while (p != NULL) {
printf("Student name: %s, age: %d, sex: %c\n", p->name, p->age, p->sex);
p = p->next;
}
return 0;
}
```
运行结果如下:
```
Delete student Lucy
Student Rose not found
Student name: Tom, age: 18, sex: M
Student name: Amy, age: 17, sex: F
Student name: Jack, age: 19, sex: M
Student name: David, age: 20, sex: M
```
以上就是代码实现和运行结果。
阅读全文