C语言链表实现学生系统多名学生信息录入
在 C 语言中,可以使用链表结构来实现学生系统的多名学生信息的录入功能。下面是一个简单的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 学生信息结构体
typedef struct Student {
char name[20];
int age;
struct Student* next;
} Student;
// 添加学生信息到链表
void addStudent(Student** head, char* name, int age) {
// 创建新的学生结点
Student* newStudent = (Student*)malloc(sizeof(Student));
strcpy(newStudent->name, name);
newStudent->age = age;
newStudent->next = NULL;
if (*head == NULL) {
// 链表为空,将新结点设为头结点
*head = newStudent;
} else {
// 找到链表的末尾,并将新结点添加到末尾
Student* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
}
// 打印学生信息链表
void printStudents(Student* head) {
Student* current = head;
while (current != NULL) {
printf("Name: %s, Age: %d\n", current->name, current->age);
current = current->next;
}
}
int main() {
Student* head = NULL; // 头结点
// 录入学生信息
addStudent(&head, "Tom", 18);
addStudent(&head, "Alice", 19);
addStudent(&head, "Bob", 20);
// 打印学生信息
printStudents(head);
// 释放链表内存
Student* current = head;
while (current != NULL) {
Student* temp = current;
current = current->next;
free(temp);
}
return 0;
}
这段代码创建了一个学生信息的链表,使用addStudent函数向链表中添加学生信息,使用printStudents函数打印学生信息链表。在main函数中,可以通过调用addStudent函数来录入学生信息,然后调用printStudents函数打印学生信息链表。最后,需要释放链表的内存空间,防止内存泄漏。
原文地址: https://www.cveoy.top/t/topic/pdu0 著作权归作者所有。请勿转载和采集!