#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct Node{
int Data;
struct Node *next;
};
struct Node* creat(){ /* 创建链表 */
struct Node *L;
L=(struct Node*)malloc(sizeof(struct Node));
L->next=NULL;
return L;
}
void suju(struct Node *L,int n){ /*存入数据 */
struct Node *p,*q;
p=L;
q=(struct Node*)malloc(sizeof(struct Node));
while(p->next!=NULL&&p->next->Data<n)
p=p->next;
q->Data=n;
q->next=p->next;
p->next=q;
}
void print(struct Node *L){
struct Node *p;
p=L->next;
while(p!=NULL){
printf("%d ",p->Data);
p=p->next;
}
printf("\n");
}
struct Node* mergeTwoLists(struct Node* list1, struct Node* list2){
struct Node *p,*q,*r,*L3;
L3=creat();
p=list1->next;
q=list2->next;
while(p!=NULL&&q!=NULL){ /* 比较大小 合并链表*/
if(p->Data < q->Data){
suju(L3,p->Data);
p=p->next;
}
else
{
suju(L3,q->Data);
q=q->next;
}
}
if(p==NULL){
while(q!=NULL){
suju(L3,q->Data);
q=q->next;
}
}
else if(q==NULL){
while(p!=NULL){
suju(L3,p->Data);
p=p->next;
}
}
return L3;
}
int main(){
struct Node *L1,*L2,*L3;
L1=creat();
L2=creat();
srand((int)time(NULL));
for(int i=0;i<10;i++){
suju(L1,rand()%100);
suju(L2,rand()%100);
}
L3=mergeTwoLists(L1,L2);
print(L1);
print(L2);
print(L3);
return 0;
}
运行结果如下: