2)建立一个链表,每个节点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的节点所包含的年龄等于此年龄,则将此节点删去。用C语言编写
时间: 2024-03-17 21:44:19 浏览: 45
可以使用以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
int id;
char name[20];
char gender;
int age;
struct student *next;
};
typedef struct student Student;
Student *createList(int n); // 创建链表
void printList(Student *head); // 输出链表
void deleteNode(Student *head, int age); // 删除指定年龄的节点
int main() {
int n, age;
printf("请输入学生人数:");
scanf("%d", &n);
Student *head = createList(n);
printf("请输入要删除的年龄:");
scanf("%d", &age);
deleteNode(head, age);
printf("\n删除后的链表:\n");
printList(head);
return 0;
}
// 创建链表
Student *createList(int n) {
Student *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Student *node = (Student *) malloc(sizeof(Student));
printf("请输入学生信息(学号 姓名 性别 年龄):");
scanf("%d %s %c %d", &node->id, node->name, &node->gender, &node->age);
node->next = NULL;
if (head == NULL) {
head = node;
} else {
tail->next = node;
}
tail = node;
}
return head;
}
// 输出链表
void printList(Student *head) {
while (head != NULL) {
printf("%d %s %c %d\n", head->id, head->name, head->gender, head->age);
head = head->next;
}
}
// 删除指定年龄的节点
void deleteNode(Student *head, int age) {
Student *p = head, *q = head->next;
while (q != NULL) {
if (q->age == age) {
p->next = q->next;
free(q);
q = p->next;
} else {
p = q;
q = q->next;
}
}
if (head->age == age) {
Student *temp = head;
head = head->next;
free(temp);
}
}
```
其中,`createList`函数用于创建链表,`printList`函数用于输出链表,`deleteNode`函数用于删除指定年龄的节点。在`main`函数中,首先输入学生人数和要删除的年龄,然后调用`createList`函数创建链表,调用`deleteNode`函数删除指定年龄的节点,最后调用`printList`函数输出链表。
阅读全文