-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstudent.c
76 lines (64 loc) · 1.77 KB
/
student.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
struct Student {
char name[50];
int age;
float grade;
struct Student* next; // 指向下一个学生节点的指针
};
// 函数声明
void addStudent(struct Student** head, char* name, int age, float grade);
void displayStudents(struct Student* head);
void freeStudents(struct Student* head);
int main() {
struct Student* head = NULL;
// 添加学生信息
addStudent(&head, "Alice", 20, 85.5);
addStudent(&head, "Bob", 22, 76.0);
addStudent(&head, "Charlie", 21, 92.3);
// 显示学生信息
displayStudents(head);
// 释放内存
freeStudents(head);
return 0;
}
// 添加学生信息到链表
void addStudent(struct Student** head, char* name, int age, float grade) {
struct Student* newStudent = (struct Student*)malloc(sizeof(struct Student));
if (newStudent == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
strcpy(newStudent->name, name);
newStudent->age = age;
newStudent->grade = grade;
newStudent->next = NULL;
if (*head == NULL) {
*head = newStudent;
} else {
struct Student* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
}
// 显示学生信息
void displayStudents(struct Student* head) {
printf("Student List:\n");
while (head != NULL) {
printf("Name: %s, Age: %d, Grade: %.2f\n", head->name, head->age, head->grade);
head = head->next;
}
}
// 释放学生链表内存
void freeStudents(struct Student* head) {
struct Student* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}