题目:已有a,b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并, 按学号升序排列。
#include<stdio.h>
typedef struct student{
int num;
double grade;
struct student *next;
}student;
student *merge(student *a,student *b){
//先将两个链表合并,在对合并后的链表排序
student *head = a;
while(a->next)
a = a->next;
a->next = b;
//使用选择排序,对链表进行排序
//最小的放在未排序的链表头部
student *pre = head;
while(pre->next){
a = pre->next;
while(a){
if(pre->num > a->num){
int num = pre->num;
double grade = pre->grade;
pre->num = a->num;
pre->grade = a->grade;
a->num = num;
a->grade = grade;
}
a = a->next;
}
pre = pre->next;
}
return head;
}
int main(){
student a[3] = {{1,79},{4,36},{5,79}};
for(int i=0;i<2;i++)
a[i].next = &a[i+1];
student b[2] = {{2,38},{6,78}};
for(int i=0;i<1;i++)
b[i].next = &b[i+1];
student *combine = merge(a,b);
while(combine){
printf("%d -> %lf\n",combine->num,combine->grade);
combine = combine->next;
}
return 0;
}
结果:
![](https://i-blog.csdnimg.cn/blog_migrate/9d9b4382463e7c4b9e769cadb9e40136.png)