线性表链表

来源:互联网 发布:js添加json元素 编辑:程序博客网 时间:2024/03/28 21:49
//输入n个学生信息(姓名,成绩),再按成绩降序输出这些信息
#include<stdio.h>
#include<stdlib.h>
//------------------------
struct student
{
 char name[10];
 float score;
 struct student *next;
};
//------------------------
struct student *insert(struct student *head)
{
 struct student *p,*pnew,*pold;
 pnew=(struct student *)malloc(sizeof(struct student));
 scanf("%s%f",pnew->name,&pnew->score);//建立新节点
 p=head;
 if(pnew->score>head->score)
 {
  pnew->next=p;
  head=pnew;
 }
 else
 {
  while(p!=NULL&&pnew->score<p->score)
  {
   pold=p;
   p=p->next;
  }
  pnew->next=p;
  pold->next=pnew;
 }
 return head;
}
//------------------------
void print(struct student *head)
{
 struct student *p=head;
 while(p!=NULL)
 {
  printf("%s%.1f/n",p->name,p->score);
  p=p->next;
 }
}
//------------------------
void main()
{
 struct student *head;
 int i,n;
 scanf("%d",&n);
 head=(struct student *)malloc(sizeof(struct student));
 scanf("%s%f",head->name,&head->score);
 head->next=NULL;
 for(i=1;i<n;i++)
 {
  head=insert(head);
 }
 print(head);
}
原创粉丝点击