原题链接:数据结构-有序线性表的有序合并 - C语言网 (dotcpp.com)
#include<stdio.h>
#include<malloc.h>
typedef struct Union{
int data;
struct Union* next;
}*node,Node;
//创建集合
node creat (int);
//获取集合的第i个元素
int GetElem (node, int);
//将元素插入集合的末尾
void ListInsert (node, int);
//输出集合
void output (node);
int main(){
int LenA,LenB,i,j,e,f;
node headA,headB,headC;
while (scanf ("%d",&LenA) !=EOF){
headA=creat(LenA);//建立集合A
scanf("%d",&LenB);
headB=creat(LenB);//建立集合B
headC=creat(0);//建立空集合C
i=1; j=1;
//任意一个集合遍历完,循环就停止
//两个指针i和j,一开始分别指向两个集合的第一个元素
//比较出小的元素,插入到C集合的后面
while (i<=LenA && j<=LenB){
e=GetElem(headA,i);
f=GetElem(headB,j);
if (e<=f){
ListInsert(headC,e);
i++;
}
else{
ListInsert(headC,f);
j++;
}
}
//将没有遍历到的元素插入C集合的后面
while (i<=LenA){
e=GetElem(headA,i);
ListInsert(headC,e);
i++;
}
while (j<=LenB){
f=GetElem(headB,j);
ListInsert(headC,f);
j++;
}
//输出C集合
output(headC);
}
return 0;
}
node creat (int n){
int i;
node h,p,q;
h=(node)malloc(sizeof(Node));
h->next=NULL;
q=h;
for (i=0;i<n;i++){
p=(node)malloc(sizeof(Node));
scanf ("%d",&(*p).data);
p->next=q->next;
q->next=p;
q=p;
}
return h;
}
int GetElem (node L, int i){
node temp0;
temp0=L;
for (int j=1;j<=i;j++){
temp0=temp0->next;
}
return temp0->data;
}
void ListInsert (node L, int e){
node temp=L,p;
while (temp->next !=NULL){
temp=temp->next;
}
p=(node)malloc(sizeof(Node));
p->data=e;
p->next=temp->next;
temp->next=p;
}
void output (node L){
node temp=L;
while (temp->next !=NULL){
temp=temp->next;
printf("%d ",temp->data);
}
printf("\n");
}