2.建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。代码
时间: 2023-12-04 18:15:54 浏览: 137
以下是基于C语言的链表实现,实现了链表的插入、遍历和根据年龄删除结点的功能。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义链表结构体
struct student {
int id;
char name[20];
char gender;
int age;
struct student *next;
};
// 插入结点
struct student *insert(struct student *head, int id, char *name, char gender, int age) {
struct student *p = (struct student *)malloc(sizeof(struct student));
p->id = id;
strcpy(p->name, name);
p->gender = gender;
p->age = age;
p->next = head;
head = p;
return head;
}
// 遍历链表
void traverse(struct student *head) {
struct student *p = head;
while (p != NULL) {
printf("id: %d, name: %s, gender: %c, age: %d\n", p->id, p->name, p->gender, p->age);
p = p->next;
}
}
// 根据年龄删除结点
struct student *delete_by_age(struct student *head, int age) {
struct student *p = head;
struct student *pre = NULL;
while (p != NULL) {
if (p->age == age) {
if (pre == NULL) {
head = p->next;
} else {
pre->next = p->next;
}
free(p);
p = (pre == NULL ? head : pre->next);
} else {
pre = p;
p = p->next;
}
}
return head;
}
int main() {
struct student *head = NULL;
head = insert(head, 1, "Alice", 'F', 18);
head = insert(head, 2, "Bob", 'M', 18);
head = insert(head, 3, "Charlie", 'M', 20);
head = insert(head, 4, "David", 'M', 19);
printf("Before delete:\n");
traverse(head);
head = delete_by_age(head, 18);
printf("After delete:\n");
traverse(head);
return 0;
}
```
代码中定义了一个 `student` 结构体,包含学号、姓名、性别和年龄四个成员变量,以及一个指向下一个结点的指针。通过 `insert` 函数实现链表结点的插入,通过 `traverse` 函数实现链表的遍历,通过 `delete_by_age` 函数实现根据年龄删除结点的功能。在主函数中,首先插入了四个结点,然后遍历了链表,接着根据年龄删除了年龄为 18 的结点,最后再次遍历链表,验证了删除操作的正确性。
阅读全文