习题2.5 两个有序链表序列的合并 (15分)
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read();
void Print( List L );
List Merge( List L1, List L2 );
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
return 0;
}
List Read(){
List L,s,p;
L=(List)malloc(sizeof(List));
p=L;
int n,x;
scanf("%d",&n);
for(int i=0;i<n;i++){
s=(List)malloc(sizeof(List));
scanf("%d",&s->Data);
p->Next=s;
p=s;
}
p->Next=NULL;
return L;
}
void Print( List L ){
if(L->Next==NULL){
printf("NULL");
}
else{
while(L->Next!=NULL){
printf("%d ",L->Next->Data);
L=L->Next;
}
}
printf("\n");
}
List Merge( List L1, List L2 )
{
List p1,p2,p,L;
p1=L1->Next;//分别遍历两个链表
p2=L2->Next;
L=(List)malloc(sizeof(List));//新的头结点
L->Data=L1->Data+L2->Data;
p=L;
while(p1!=NULL&&p2!=NULL)
{
if((p1->Data)<(p2->Data))
{
p->Next=p1;
p=p->Next;
p1=p1->Next;
}
else
{
p->Next=p2;
p=p->Next;
p2=p2->Next;
}
}
if(p1==NULL)
{
p->Next=p2;
}
else if(p2==NULL)
{
p->Next=p1;
}
L1->Next=NULL;
L2->Next=NULL;
return L;
}