本帖最后由 Neverturnback 于 2019-8-6 13:24 编辑 /*
要求:1.设计一个程序,用链表储存学生信息,并以成绩进行排序输出;
2.学生信息用结构体进行封装;
*/
#include<stdio.h>
#include<stdlib.h>
struct STUDENT//学生信息结构体
{
char name[20];
int age;
float score;
char num[20];
};
struct NODE
{
struct STUDENT data;//使用结构体封装
struct NODE* next;
};
struct NODE* CreateLink(void);//创建链表函数声明
void lnitLink(struct NODE *);//链表结点信息输入函数声明
void BubbleSort(struct NODE *);//链表结点排序函数声明
void OutputLink(struct NODE *);//链表结点信息输出函数声明
int main(void)
{
struct NODE * head = CreateLink();//创建链表
lnitLink(head);//链表初始化
BubbleSort(head);//冒泡排序
printf("\n*************************排序后的结果如下:******************************\n\n");
OutputLink(head);//排序结果输出
return 0;
}
//****************以下为创建链表函数***********************************
struct NODE* CreateLink(void)
{
int i = 0;
int cnt = 0;
struct NODE * head = (struct NODE *)malloc(sizeof(struct NODE));
struct NODE * move = head;
move->next = NULL;
printf("请输入学生的数量:");
scanf("%d", &cnt);
getchar();
for (i = 0; i < cnt; ++i)
{
struct NODE* fresh = (struct NODE *)malloc(sizeof(struct NODE));
move->next = fresh;
fresh->next = NULL;
move = fresh;
}
return head;
}
//****************以下为链表信息输入函数***********************************
void lnitLink(struct NODE *head)
{
int i = 1;
struct NODE* move = head->next;
while (NULL != move)
{
printf("\n请输入第%d个学生的姓名、年龄、成绩、学号:\n\n", i);
scanf("%s%d%f%s", move->data.name, &move->data.age, &move->data.score, move->data.num);
getchar();
move = move->next;
++i;
}
return;
}
//******************以下为冒泡排序函数************************************************
void BubbleSort(struct NODE* head)
{
struct NODE* move = head->next;
struct NODE* turn = head->next;
struct STUDENT buf;
if (NULL == move)
{
printf("链表为空\n");
exit(0);//退出程序
}
while (NULL != turn->next)
{
while (NULL != move->next)
{
if (move->data.score < move->next->data.score)
{
buf = move->data;
move->data = move->next->data;
move->next->data = buf;
}
move = move->next;
}
move = head->next;
turn = turn->next;
}
return;
}
//*******************以下为链表输出函数***************************************
void OutputLink(struct NODE* head)
{
struct NODE* move = head->next;//初始化为首结点
while (NULL != move)
{
printf("[姓名:%s 年龄:%d 成绩:%.1f 学号:%s]\n\n", move->data.name, move->data.age, move->data.score, move->data.num);
move = move->next;
}
getchar();
getchar();
return;
}
你所有的malloc的部分都出错了,帮你修改过了,还有malloc分配的空间最后记得free释放,释放我没帮你写,你自己加把
|