#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode{//指向结构体成员 必然是结构体指针
int data;
struct LNode *next;
}LNode,*LinkList;
void InitList(LinkList &L){//构造空线性表L
L = (LinkList)malloc(sizeof(struct LNode));//产生头结点 L
if(!L)//存储分配失败
exit(0);
L -> next = NULL; //头结点指针域为空
}
void CreateList(LinkList &La,LinkList &Lb){
int i;
int a[3] = {4,7,11} ;
int b[3] = {3,6,9};
LinkList pnew,pa,pb;
pb = Lb;
pa = La;
for(i=0; i < 3; i++){
pnew = (LinkList)malloc(sizeof(LNode)) ;
pnew -> data =a[i];
pnew->next = NULL;
pa ->next = pnew;
pa = pnew;
}
for(i=0; i < 3; i++){
pnew = (LinkList)malloc(sizeof(LNode)) ;
pnew -> data =b[i];
pnew->next = NULL;
pb ->next = pnew;
pb = pnew;
}
}
//将b集合元素依次取出 存放在临时变量pb1 中依次插入a集合中
void merg(LinkList &La,LinkList Lb)
{
LinkList pa,pb,pa1,pb1;
int e;
pa = La;//内存循环
pb = Lb;//外层循环
pa1 = La;
pb1 = Lb;//取出b集合中的元素,存放在pb1中
pb = pb ->next;//pb第一次循环指向第一个元素
while(pb)
{ pb1 = pb;
e = pb1 ->data;
//printf("%d",e);
pb = pb ->next;
while(pa)
{
pa1 = pa;//记取pa结点
pa = pa ->next;//获取pa下一个结点
//printf("%d",pa->data);
if(e <= pa ->data)//符合小于pa结点元素的条件插入
{
pb1 ->next = pa;//存取当前b元素的结点临时变量pb1 next 指向当前pa
pa1 ->next = pb1;//pa1为当前pa的上一个结点 他指向pb1
pa = La; //插入成功后 pa为头结点 退出循环 寻找b集合第二个元素
break;
}
if(pa == NULL)//当b集合某个元素大于a集合所有元素 插入末尾结点
{
pa ->next = pb1;
pb1 ->next =NULL;
pa = La;
}
}
}
}
void output(LinkList L){
L = L->next;
while(L){
printf("%d
",L->data);
L = L->next;
}
}
void DestroyList(LinkList &L){
LinkList q;
while(L){
q = L -> next;
free(L);
L = q;
}
}
int main(){
LinkList La,Lb;
InitList(La);
InitList(Lb);
CreateList(La,Lb);
merg(La,Lb);
output(La);
//DestroyList(La);
DestroyList(Lb);
return 0;
}