c语言单链表增加学生信息函数
时间: 2023-11-04 08:03:19 浏览: 66
要编写一个C语言函数,用于增加学生信息到单链表中。以下是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[50];
int age;
float score;
struct student *next;
};
// 在链表末尾添加学生信息
void addStudent(struct student **head, char name[], int age, float score)
{
struct student *newStudent = (struct student*)malloc(sizeof(struct student));
strcpy(newStudent->name, name);
newStudent->age = age;
newStudent->score = score;
newStudent->next = NULL;
if (*head == NULL) {
*head = newStudent;
} else {
struct student *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
}
int main()
{
struct student *head = NULL;
addStudent(&head, "Alice", 20, 85.5);
addStudent(&head, "Bob", 21, 78.0);
addStudent(&head, "Carol", 19, 92.3);
struct student *current = head;
printf("学生信息列表:\n");
while (current != NULL) {
printf("姓名:%s, 年龄:%d, 成绩:%.1f\n", current->name, current->age, current->score);
current = current->next;
}
return 0;
}
```
这个示例中,我们定义了一个结构体`student`用于保存学生信息,并包含一个指针`next`指向下一个学生的节点。`addStudent`函数用于往链表末尾添加新的学生信息。头指针参数`head`用于维护链表的头指针,我们使用二级指针的形式传递头指针,以方便在函数内部修改头指针的值。函数内部首先创建一个新的节点`newStudent`,并将学生信息填充到节点的各个字段中,然后通过遍历链表找到末尾节点将新节点插入。如果链表为空,直接将新节点设为头指针即可。在`main`函数中,我们通过多次调用`addStudent`函数来增加学生信息,然后遍历整个链表打印各个学生信息。