题目描述
已有a、b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按学号升序排列。
输入
第一行,a、b两个链表元素的数量N、M,用空格隔开。 接下来N行是a的数据 然后M行是b的数据 每行数据由学号和成绩两部分组成
输出
按照学号升序排列的数据
样例输入
2 3 5 100 6 89 3 82 4 95 2 10
样例输出
2 10 3 82 4 95 5 100 6 89
#include <stdio.h>
#include <malloc.h>
typedef struct Student
{
int num;
int grade;
struct Student *next;
}*node,Node;
node buildf(int n);//创建链表
void sortf(node l1,node l2);//连接与排序
void print(node l);//输出
int main()
{
int n,m;
scanf("%d%d",&n,&m);
node head1,head2;
head1=buildf(n);
head2=buildf(m);
sortf(head1,head2);
return 0;
}
node buildf(int n)
{
node h;
h=(node)malloc(sizeof(Node));
h->next=NULL;
node p1=h,p2;
int i;
for(i=0;i<n;i++)
{
p2=(node)malloc(sizeof(Node));
scanf("%d%d",&p2->num,&p2->grade);
p2->next=p1->next;
p1->next=p2;
p1=p2;
}
return h;
}
void sortf(node l1,node l2)
{
node q;
q=l1;
l2=l2->next;
while(q->next!=NULL)
{
q=q->next;
}
q->next=l2;
q=l1->next;
node min,p;
int t,n,g;
while(q!=NULL)
{
p=q;
t=p->num;
min=p;
while(p!=NULL)
{
if(p->num<t)
{
t=p->num;
min=p;
}
p=p->next;
}
n=q->num;
q->num=min->num;
min->num=n;
g=q->grade;
q->grade=min->grade;
min->grade=g;
q=q->next;
}
print(l1);
}
void print(node l)
{
l=l->next;
node q;
while(l!=NULL)
{
printf("%d %d\n",l->num,l->grade);
q=l;
l=l->next;
free(q);
}
}