用C 语言构造学生信息链表,学生信息应包括姓名和年龄(链表初始化),根据自己的需要建立链表添加学生信息,学生信息不得少于3条(建立链表:头插法或者尾插法皆可) 3.打印出所有学生的信息(遍历),并统计学生人数(求链表长度) 4.在第二个位置插入一个学生信息,姓名为Tom,年龄为10(链表插入),并打印出插入后的学生信息表(遍历) 5.查找年龄为10的学生,打印其姓名(按值查找) 6.删除第二个学生的信息(删除),打印删除后的学生信息表(遍历)
时间: 2023-11-13 18:05:57 浏览: 83
以下是用C语言实现的学生信息链表,包括链表初始化、添加学生信息、遍历链表、插入学生信息、查找学生信息和删除学生信息。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct student {
char name[20];
int age;
struct student *next;
} Student;
// 初始化链表
Student *init_list() {
Student *head = (Student*)malloc(sizeof(Student));
head->next = NULL;
return head;
}
// 添加学生信息
void add_student(Student *head, char *name, int age) {
Student *p = (Student*)malloc(sizeof(Student));
strcpy(p->name, name);
p->age = age;
p->next = head->next;
head->next = p;
}
// 遍历链表并统计学生人数
int traverse_list(Student *head) {
int count = 0;
Student *p = head->next;
while (p != NULL) {
printf("name: %s, age: %d\n", p->name, p->age);
p = p->next;
count++;
}
return count;
}
// 在第二个位置插入学生信息
void insert_student(Student *head, char *name, int age) {
Student *p = (Student*)malloc(sizeof(Student));
strcpy(p->name, name);
p->age = age;
p->next = head->next->next;
head->next->next = p;
}
// 查找年龄为指定值的学生
char* find_student(Student *head, int age) {
Student *p = head->next->next;
while (p != NULL) {
if (p->age == age) {
return p->name;
}
p = p->next;
}
return NULL;
}
// 删除第二个学生的信息
void delete_student(Student *head) {
Student *p = head->next->next;
head->next->next = p->next;
free(p);
}
int main() {
Student *head = init_list();
add_student(head, "Alice", 18);
add_student(head, "Bob", 20);
add_student(head, "Charlie", 22);
printf("All students:\n");
int count = traverse_list(head);
printf("Total count: %d\n", count);
printf("\nInsert a student:\n");
insert_student(head, "Tom", 10);
traverse_list(head);
printf("\nFind a student:\n");
char *name = find_student(head, 10);
if (name != NULL) {
printf("The name of the student is %s.\n", name);
} else {
printf("No student with this age.\n");
}
printf("\nDelete a student:\n");
delete_student(head);
traverse_list(head);
return 0;
}
```
阅读全文