C语言链表班级成员举例
时间: 2023-11-10 11:06:53 浏览: 68
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char name[20];
int age;
int id;
struct student *next;
} Student;
Student *create_student(char name[], int age, int id);
void add_student(Student **head, Student *new_student);
void print_student_list(Student *head);
void free_student_list(Student **head);
int main(void) {
Student *head = NULL;
// create some students
Student *s1 = create_student("Alice", 20, 1001);
Student *s2 = create_student("Bob", 21, 1002);
Student *s3 = create_student("Charlie", 22, 1003);
Student *s4 = create_student("David", 23, 1004);
// add them to the list
add_student(&head, s1);
add_student(&head, s2);
add_student(&head, s3);
add_student(&head, s4);
// print the list
print_student_list(head);
// free the list
free_student_list(&head);
return 0;
}
// create a new student with the given name, age, and id
Student *create_student(char name[], int age, int id) {
Student *new_student = malloc(sizeof(Student));
strcpy(new_student->name, name);
new_student->age = age;
new_student->id = id;
new_student->next = NULL;
return new_student;
}
// add a new student to the list
void add_student(Student **head, Student *new_student) {
if (*head == NULL) {
*head = new_student;
} else {
Student *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_student;
}
}
// print out the list of students
void print_student_list(Student *head) {
printf("Class members:\n");
Student *current = head;
while (current != NULL) {
printf("%s, age %d, id %d\n", current->name, current->age, current->id);
current = current->next;
}
}
// free the memory used by the list of students
void free_student_list(Student **head) {
Student *current = *head;
while (current != NULL) {
Student *next = current->next;
free(current);
current = next;
}
*head = NULL;
}
阅读全文