建立一个成绩按降序排列的链表

/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co.,     Ltd. 
File name:
Author:fhb    Version:0.1    Date: 
Description:
Funcion List:
五、编写程序
STUDENT *Create(STUDENT studs[],int n)。
STUDENT是一个结构类型,包含姓名、成绩和指针域。
studs数组中存储了n个STUDENT记录。
create函数的功能是根据studs数组建立一个链表
,链表中结点按成绩降序排列,函数返回链表头指针。
*****************************************************/


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


typedef struct student
{
char name[20];
int score;
struct student * next;
}STUDENT;


typedef STUDENT * Link;


STUDENT *Create(STUDENT studs[], int n);
void create_empty_list(Link * head);
void create_newnode(Link * new_node);
void is_malloc_ok(Link new_node);
void insert_node_sort(Link *head, Link new_node);
void display_list(Link head);




int main()
{
Link head = NULL;
int num;
int i;
Link studs = NULL;

printf("please input the number of students:");
scanf("%d", &num);
studs = (Link)malloc(num*sizeof(STUDENT));
for (i = 0; i < num; i++)
{
printf("name%d=", i);
scanf("%s", studs[i].name);
printf("score%d=", i);
scanf("%d", &studs[i].score);
}

printf("primary data are:\n");
printf("name\t\tscore\n");
for (i = 0; i <num; i++)
{
printf("%s\t\t%d\n", studs[i].name, studs[i].score);
}

printf("after the sort:\n");
head = Create(studs,num);
display_list(head);

return 0;
}


void display_list(Link head)
{
Link p;
p = head;
printf("name\t\tscore\n");
while (p != NULL)
{
printf("%s\t\t%d\n", p->name,p->score);
p = p->next;
}
}


STUDENT *Create(STUDENT studs[], int n)
{
Link head = NULL;
Link new_node = NULL;
int i;
create_empty_list(&head);
for (i = 0; i < n; i++)
{
new_node = &studs[i];
//create_newnode(&new_node);
insert_node_sort(&head, new_node);
}
return head;
}


void create_empty_list(Link *head)
{
*head = NULL;
}


/*void create_newnode(Link * new_node)
{
*new_node = (Link)malloc(sizeof(STUDENT));
is_malloc_ok(*new_node);
}*/


void is_malloc_ok(Link new_node)
{
if (new_node == NULL)
{
printf("malloc error!\n");
exit(-1);
}
}


void insert_node_sort(Link *head, Link new_node)
{
Link p, front;
p = *head;
if (*head == NULL)
{
new_node->next = *head;
*head = new_node;
}
else
{
front = *head;
p = *head;
while (p != NULL&&new_node->score <= p->score)
{
front = p;
p = p->next;
}
if (p == *head)
{
new_node->next = *head;
*head = new_node;
}
else
{
new_node->next = p;
front->next = new_node;
}
}

}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值