/*已有a、b两个链表,每个链表中的结点包括学号、成绩。要求
把两个链表合并,按学号升序排列。*/
#include"stdio.h"
#include"stdlib.h"
#define LEN sizeof(Stu)
typedef struct Student
{
int num;
float score;
struct Student *next;
}Stu;
void main()
{
Stu *Creat();
Stu *Insert(Stu *ahead,Stu *bhead);
void Print(Stu *head);
Stu *ahead,*bhead,*abhead;
printf("input list a:\n");
ahead=Creat();
Print(ahead);
printf("input list b:\n");
bhead=Creat();
Print(bhead);
printf("The mixed:\n");
abhead=Insert(ahead,bhead);
Print(abhead);
}
//建立链表的函数
Stu *Creat()
{
Stu *p1,*p2,*head;
p1=p2=(Stu*)malloc(LEN);
scanf("%d %f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
if(head==NULL)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(Stu*)malloc(LEN);
scanf("%d %f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
//输出链表的函数
void Print(Stu *head)
{
Stu *p;
p=head;
if(head!=NULL)
{
while(p!=NULL)//不能写成:p->next!=NULL
{
printf("number:%d
score:%5.1f\n",p->num,p->score);
p=p->next;
}
}
}
//合并排序函数
Stu *Insert(Stu *ahead,Stu *bhead)
{
Stu *pa1,*pa2,*pb1,*pb2;
pa1=ahead;
pb1=bhead;
pb2=pb1;
if(ahead==NULL)
return bhead;
if(bhead==NULL)
return ahead;
do
//让链表b中的结点依次和a中的结点比较并插入
{
pb1=pb2;
pa1=ahead;
while((pb1->num>pa1->num)&&(pa1->next!=NULL))
{
pa2=pa1;
pa1=pa1->next;
}
if(pb1->num<=pa1->num)
{
if(pa1==ahead)
ahead=pb1;
else
pa2->next=pb1;
pb2=pb1->next;
pb1->next=pa1;
//pb1=pb2;
}
else
{
pa1->next=pb1;
pb2=pb1->next;
pb1->next=NULL;
//pb1=pb2;
}
// pb2=pb2->next;
}while(pb2!=NULL);
return ahead;
}
/*亲测!!!
*/