C语言学习历程——编程练习3——05

来源:互联网 发布:linux发行版 编辑:程序博客网 时间:2024/05/16 06:43

5.  编写程序STUDENT *Create(STUDENT studs[],int n)。
  STUDENT是一个结构类型,包含姓名、成绩和指针域。
  studs数组中存储了n个STUDENT记录。
  create函数的功能是根据studs数组建立一个链表,
  链表中结点按成绩降序排列,函数返回链表头指针。


分析:首先创建学生结构体,先把数据 排序好,然后再链接成链表。


下面是代码实现:


/***************************************************

  编写程序STUDENT *Create(STUDENT studs[],int n)。
  STUDENT是一个结构类型,包含姓名、成绩和指针域。
  studs数组中存储了n个STUDENT记录。
  create函数的功能是根据studs数组建立一个链表,
  链表中结点按成绩降序排列,函数返回链表头指针。
***************************************************/


#include <stdio.h>
#include <stdlib.h>


struct student  //创建学生结构体
{
char name[20];
int score;
struct student *next;
};


typedef struct student STUDENT;


STUDENT *Create(STUDENT *studs, int n)
{
int i = 0;
int j = 0;
STUDENT t;
STUDENT *head;


for (i = 0; i < n - 1; i++) //冒泡排序
{
for (j = 0; j < n - 1 - i; j++)
{
if (studs[j].score < studs[j + 1].score)
{
t = studs[j];
studs[j] = studs[j + 1];
studs[j + 1] = t;
}
}
}


head = &studs[0];


for (i = 0; i < n - 1; i++) //链接成链表
{
studs[i].next = &studs[i + 1];
}
studs[i].next = NULL;


return head;
}


void Display(STUDENT *head)     //打印链表节点数据
{
STUDENT *p = head;


while (p != NULL)
{
printf ("%s  %d", p -> name, p -> score);
printf ("\n");
p = p -> next;
}
}


int main()
{
STUDENT studs[40];
int n = 0;
int i = 0;
STUDENT *head;


printf ("How many students : ");
scanf ("%d", &n);
printf ("Please input the name and scores : \n");


for (i = 0; i < n; i++)
{
getchar();
scanf ("%s%d", studs[i].name, &studs[i].score); //接收学生的数据
}


head = Create(studs, n);


printf ("Large to small:\n"); //打印结果
Display(head);


return 0;
}
0 0