#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();
int n,m,i,j;
printf("请输入链表L1的长度n:\n") ;
scanf("%d",&n);
int arr1[n];
printf("链表L1的长度为:%d\n",n);
for(i=0;i<n;i++){
printf("请输入第%d个值:\n",i+1);
scanf("%d",&arr1[i]);
}
printf("请输入链表L2的长度m:\n");
scanf("%d",&m);
int arr2[m];
printf("链表L2的长度为:%d\n",m);
for(j=0;j<m;j++){
printf("请输入第%d个值:\n",j+1);
scanf("%d",&arr2[j]);
}
for(i=0;i<n;i++){
suju(L1,arr1[i]);
}
for(j=0;j<m;j++){
suju(L2,arr2[j]);
}
L3=mergeTwoLists(L1,L2);
print(L1);
print(L2);
print(L3);
return 0;
}
运行结果如下: