C语言程序设计教程(第三版)课后习题11.8

来源:互联网 发布:第一军团永远忠诚知乎 编辑:程序博客网 时间:2024/05/16 18:48

题目描述

已有a、b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按学号升序排列。 使用结构体

输入

第一行,a、b两个链表元素的数量N、M,用空格隔开。接下来N行是a的数据然后M行是b的数据每行数据由学号和成绩两部分组成

输出

按照学号升序排列的数据

样例输入

2 35 1006 893 824 952 10

样例输出

2 103 824 955 100

6 89

【代码】

#include <stdio.h>#include <malloc.h>struct stu{    int num;    int score;    struct stu *next;};struct stu *create(int n)       //创建链表 {    struct stu *head=NULL,*tail,*p;    int i;    for(i=1;i<=n;i++)    {        p=malloc(sizeof(struct stu));        scanf("%d%d",&p->num,&p->score);        if(head==NULL)            head=p;        else            tail->next=p;        tail=p;    }    tail->next=NULL;    return head;}struct stu *heBin(struct stu *h1,struct stu *h2)    //合并链表 {    struct stu *p=h1;    while(p->next)        p=p->next;    p->next=h2;    return h1;}struct stu *sort(struct stu *head)            //链表排序 {    struct stu *end,*p;    int t;    end=head;    while(end)        end=end->next;    while(head->next!=end)    {        p=head;        while(p->next!=end)        {            if(p->num>p->next->num)            {                t=p->num;                p->num=p->next->num;                p->next->num=t;                t=p->score;                p->score=p->next->score;                p->next->score=t;            }            p=p->next;        }        end=p;    }    return head;    } void print(struct stu *head)        //输出链表 {    struct stu *p;    while(head)    {        p=head;        head=head->next;        printf("%d %d\n",p->num,p->score);        free(p);    }}main(){    struct stu *h1,*h2,*head;    int n,m;    scanf("%d%d",&n,&m);    h1=create(n);    h2=create(m);    head=heBin(h1,h2);    head=sort(head);     print(head);    } 


阅读全文
0 0
原创粉丝点击