学习记录
freopen函数的使用
链表的操作
排序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 4
//要求成绩从大到小排序!!
struct DATA
{
int id;
char name[15];
int score;
};
typedef struct DATA data;
struct student
{
data inf;
struct student *next;
};
typedef struct student stu;
void sort(data a[])
{
data tmp;
int i,j;
for(i=0;i<N-1;i++)
{
for(j=i+1;j<N;j++)
{
if(a[i].score<a[j].score)
{
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
}
}
stu *create(stu *head)
{
head=(stu*)malloc(sizeof(stu));
if(head==NULL)
{
printf("内存分配失败!\n");
exit(1);
}
head->next=NULL;
return head;
}
stu *append(stu *head,data a)
{
stu *p,*pre=head;
p=(stu*)malloc(sizeof(stu));
if(p==NULL)
{
printf("内存分配失败!\n");
exit(1);
}
p->inf.id=a.id;
strcpy(p->inf.name,a.name);
p->inf.score=a.score;
while(pre->next!=NULL)
{
pre=pre->next;
}
pre->next=p;
p->next=NULL;
return head;
}
void disp(stu *head)
{
stu *p=head->next;
while(p)
{
printf("%-3d%-15s%-3d\n",p->inf.id,p->inf.name,p->inf.score);
p=p->next;
}
}
int main()
{
freopen("a.txt","r",stdin);
freopen("b.txt","w",stdout);
stu *head=NULL;
data a[10];
int i;
int id;
char name[15];
int score;
//读数据
i=0;
while (scanf("%d%s%d", &id, name, &score) != EOF && i<N) // 这是未指定数据量读入的通用方法,需要记住
{
a[i].id = id;
strcpy(a[i].name, name);
a[i].score = score;
i++;
}
for(i=0;i<N;i++)
{
scanf("%d%s%d",&a[i].id,a[i].name,&a[i].score);
}
sort(a);
//创建链表
head=create(head);
//增加结点
for(i=0;i<N;i++)
{
head=append(head,a[i]);
}
disp(head);
fclose(stdin);
fclose(stdout);
return 0;
}