将一个有序链表和一个无序链表合并,并按序号大小排序
这里做的工作有很大局限性:未考虑两链表中序号相同时怎么办;
表一必须是有序的,表二可以是无序的,这样能排序;
感觉两个都是乱序的很难弄。
但调了很久,记下纪念。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LA 4
#define LB 4
#define NULL 0
struct student
{int num;
char name[8];
struct student *next;
}a[LA],b[LB];
void main()
{struct student a[LA]={{101,"Wang"},{102,"LI"},{105,"zhang"},{106,"Wei"}};
struct student b[LB]={{108,"Zhang"},{104,"Ma"},{107,"Guo"},{100,"Lui"}};
int i;
struct student *p,*pt,*p1,*p2,*head1,*head2,*p3,*p4;
head1=a;
head2=b;
printf("list a:\n");
for(p1=head1,i=1;p1<a+LA;i++)
{
pt=p1;
p1->next=a+i;
printf("%8d%8s\n",p1->num,p1->name);
p1=p1->next;
}
pt->next=NULL;
printf("list b:\n");
for(p2=head2,i=1;p2<b+LB;i++)
{p=p2;
p2->next=b+i;
printf("%8d%8s\n",p2->num,p2->name);
p2=p2->next;
}
p->next=NULL;
printf("\n");
p1=head1;
p2=head2;
p3=head1;
while(1)
{
while(p1->num<p2->num)
{
if(p1->next==NULL)
{
if(p2->next!=NULL)
{
p1->next=p2;
p4=p2->next;
p2->next=NULL;
p3=p1;
p1=p2;
p2=p4;
}
else
{
p1->next=p2;
goto loop;
}
}
else
{
p3=p1;
p1=p1->next;
}
// printf("%7d %7s\n",p3->num,p3->name);
//printf("%7d %7s\n",p1->num,p1->name);
// printf("\n");
}
while(p1->num>p2->num)
{
if(p2->next!=NULL)
{
if(p1!=head1)
{
if(p3->num<p2->num)
{
p3->next=p2;
p4=p2->next;
p2->next=p1;
p3=p2;
p2=p4;
}
else
{
p1=head1;
p3=head1;
break;
}
}
else
{
p3=p2;
p4=p2->next;
p2->next=p1;
p3=p2;
head1=p3;
p2=p4;
}
}
else
{
if(p1!=head1)
{
if(p3->num<p2->num)
{
p3->next=p2;
p2->next=p1;
goto loop;
}
else
{
p1=head1;
p3=head1;
break;
}
}
else
{
p3=p2;
p2->next=p1;
head1=p3;
goto loop;
}
}
}
}
loop: ;
p1=head1;
printf("\n result:\n");
while(p1!=NULL)
{
printf("%7d %7s\n",p1->num,p1->name);
p1=p1->next;
}
system("pause");
}