C语言用链表写一个有3名学生信息,插入一名学生信息
时间: 2024-02-01 22:15:18 浏览: 23
以下是用链表实现的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct student {
char name[20];
int age;
char gender[5];
struct student *next;
} Student;
int main() {
// 初始化3个学生信息
Student *stu1 = (Student *) malloc(sizeof(Student));
strcpy(stu1->name, "Tom");
stu1->age = 18;
strcpy(stu1->gender, "male");
stu1->next = NULL;
Student *stu2 = (Student *) malloc(sizeof(Student));
strcpy(stu2->name, "Lucy");
stu2->age = 19;
strcpy(stu2->gender, "female");
stu2->next = NULL;
Student *stu3 = (Student *) malloc(sizeof(Student));
strcpy(stu3->name, "Jack");
stu3->age = 20;
strcpy(stu3->gender, "male");
stu3->next = NULL;
// 将3个学生信息连接起来形成链表
stu1->next = stu2;
stu2->next = stu3;
// 新增一个学生信息
Student *newStu = (Student *) malloc(sizeof(Student));
strcpy(newStu->name, "Lily");
newStu->age = 21;
strcpy(newStu->gender, "female");
// 将新学生信息插入到链表中
newStu->next = stu2->next;
stu2->next = newStu;
// 遍历链表并输出学生信息
Student *p = stu1;
while (p != NULL) {
printf("Name: %s, Age: %d, Gender: %s\n", p->name, p->age, p->gender);
p = p->next;
}
// 释放内存
free(stu1);
free(stu2);
free(stu3);
free(newStu);
return 0;
}
```
运行结果如下:
```
Name: Tom, Age: 18, Gender: male
Name: Lucy, Age: 19, Gender: female
Name: Lily, Age: 21, Gender: female
Name: Jack, Age: 20, Gender: male
```