#include <stdio.h>
#include <stdlib.h>
/** 习题2.5 两个有序链表序列的合并 (15 分)
*
* L1和L2是给定的带头结点的单链表,
*其结点存储的数据是递增有序的;
*函数Merge要将L1和L2合并为一个非递减的整数序列。
*应直接使用原序列中的结点,
*返回归并后的带头结点的链表头指针。
*
*/
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(){
List head,pnew,ptail;
pnew=(List)malloc(sizeof(struct Node));
pnew->Next=NULL;
head=pnew;
ptail=pnew;
int n,i=0;
scanf("%d",&n);
for(i;i<n;i++){
pnew=(List)malloc(sizeof(struct Node));
scanf("%d",&pnew->Data);
ptail->Next=pnew;
ptail=pnew;
ptail->Next=NULL;
}
return head;
}
void Print( List L ){
List p;
for(p=L->Next;p;p=p->Next){
printf("%d ",p->Data);
}
printf("\n");
}
List Merge( List L1, List L2 ){
List CreatListhead;//标记头结点
List pL1,PL2;
CreatListhead=(List)malloc(sizeof(struct Node));
CreatListhead->Next=NULL;
List creatList=CreatListhead;//合并链表
pL1=L1->Next;
PL2=L2->Next;
while(pL1&&PL2){
if(pL1->Data<=PL2->Data){
creatList->Next=pL1;
creatList=pL1;
pL1=pL1->Next;
}
else {
creatList->Next=PL2;
creatList=PL2;
PL2=PL2->Next;
}
}
if(pL1==NULL)
creatList->Next=PL2;
else if(PL2==NULL)
creatList->Next=pL1;
L1->Next=NULL;
L2->Next=NULL;
return CreatListhead;
}
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L1);
Print(L2);
Print(L);
return 0;
}