#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void CreateList(LinkList &L,int n){
L=(LinkList)malloc(sizeof(LNode));
L=NULL;
LinkList r;
r=(LinkList)malloc(sizeof(LNode));
LinkList p;
int i;
for(i=0;i<n;i++){
p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
if(L==NULL){
r=p;
L=p;
}else{
r->next=p;
r=p;}
}
r->next=NULL;
}
void Visit(LinkList L){
while(L)
{
printf("%d ",L->data);
L=L->next;
}
}
void MergeList(LinkList &H1,LinkList &H2){
LinkList phead = H1;
LinkList p= H1->next;
LinkList q= H2;
if(H1->data > H2->data)
{
phead = H2;
p = H2->next;
q = H1;
}
LinkList s = phead;
while(p!=NULL && q!=NULL)
{
if(p->data < q->data)
{
s->next = p;
p = p->next;
s = s->next;
}
else if(p->data>q->data)
{
s->next = q;
q = q->next;
s = s->next;
}
else
{
s->next = p;
p = p->next;
q = q->next;
s = s->next;
}
}
if(p == NULL)//主链表先遍历完,说明另一链表还有数据得接过来
{
s->next = q;
}
if(q == NULL)//另一链表先遍历完,因为此时主链表的结构已经发生变化,所以仍需拼接过来
{
s->next = p;
}
H1=phead;
}
int main(){
LinkList p;
CreateList(p,3);
Visit(p);
printf("
");
LinkList q;
CreateList(q,3);
Visit(q);
printf("
");
MergeList(p,q);
Visit(p);
printf("
");
return 0;
}
运行结果