单向链表 排序 文件输入输出

学习记录

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值