C语言链表实现学生信息录入系统
要实现学生系统的添加功能,可以使用链表结构来存储多名学生的信息。下面是一个使用链表结构的C语言示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 学生信息结构体
typedef struct Student {
char name[50];
int age;
struct Student *next;
} Student;
// 添加学生信息
void addStudent(Student **head) {
// 创建新的学生节点
Student *newStudent = (Student*)malloc(sizeof(Student));
printf('请输入学生姓名:');
scanf('%s', newStudent->name);
printf('请输入学生年龄:');
scanf('%d', &(newStudent->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('姓名:%s 年龄:%d\n', current->name, current->age);
current = current->next;
}
}
// 释放链表内存
void freeStudents(Student *head) {
Student *current = head;
while (current != NULL) {
Student *temp = current;
current = current->next;
free(temp);
}
}
int main() {
Student *head = NULL; // 头节点指针初始化为空
int choice;
do {
printf('\n学生系统菜单\n');
printf('1. 添加学生信息\n');
printf('2. 打印学生信息\n');
printf('0. 退出\n');
printf('请输入选项:');
scanf('%d', &choice);
switch (choice) {
case 1:
addStudent(&head);
break;
case 2:
printStudents(head);
break;
case 0:
freeStudents(head);
break;
default:
printf('无效选项!\n');
}
} while (choice != 0);
return 0;
}
这个示例代码中,通过Student结构体定义了学生的信息,包括姓名和年龄,并且定义了一个指针next用于指向下一个学生的节点。addStudent函数用于添加学生信息,会依次输入学生的姓名和年龄,并将学生节点插入到链表的末尾。printStudents函数用于打印学生信息,遍历链表并逐个打印学生的姓名和年龄。freeStudents函数用于释放链表的内存。在main函数中,使用一个循环菜单来操作学生系统,用户可以选择添加学生信息、打印学生信息或退出程序。
原文地址: https://www.cveoy.top/t/topic/pduG 著作权归作者所有。请勿转载和采集!