#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student
{
char name[40];
float score;
struct Student *next;
};
void inputInfo(struct Student *);
void addStudent(struct Student **);
void printfInfo(struct Student *);
void releaseInfo(struct Student **);
void inputInfo(struct Student *stu)
{
printf("请输入学生姓名:");
scanf("%s", stu->name);
printf("请输入学生成绩:");
scanf("%f", &stu->score);
}
void addStudent(struct Student **list_head)
{
struct Student *stu;
struct Student *temp;
stu = (struct Student *)malloc(sizeof(struct Student)); // 为新建的学生创建内存空间
if (stu == NULL)
{
printf("内存申请失败!");
exit(1);
}
inputInfo(stu);
// 修改头指针的值,改为新增元素的地址,也就是stu;
// 对list_head解引用,就是头指针的值
if (*list_head != NULL)
{
temp = *list_head;
*list_head = stu;
stu -> next = temp;
}
else
{
*list_head = stu;
stu -> next = NULL;
}
}
void printInfo(struct Student *stu)
{
int count = 1;
while(stu != NULL)
{
printf("编号:%d\n", count);
printf("姓名:%s\n", stu->name);
printf("成绩:%.2f\n", stu->score);
printf("-----------------\n");
stu = stu -> next;
count++;
}
}
void releaseInfo(struct Student **stu)
{ struct Student *temp;
while (*stu != NULL)
{
temp = *stu;
*stu = (*stu)->next;
free(temp);
}
}
/*
temp = stu;
stu = stu->next;
free(temp);
*/
int main(void)
{
int ch;
struct Student *list_head;
list_head = NULL;
while(1)
{
printf("是否输入学生信息(y/n):");
do
{
ch = getchar();
}while (ch != 'y' && ch != 'n');
if (ch == 'y')
{
addStudent(&list_head);
}
else
{
break;
}
}
printf("是否打印成绩信息(y/n):");
do
{
ch = getchar();
}while(ch != 'y' && ch != 'n');
if (ch == 'y')
{
printf("\n----成绩单----\n\n");
printInfo(list_head);
}
releaseInfo(&list_head);
// releaseInfo(list_head);
return 0;
}
网友评论