算法思想:依次取La,Lb中较小的元素插入Lc中,直到一条链元素全部元素全部插入Lc中,将另外一条链中元素依次插入Lc中,最后释放La,Lb存储空间。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int ElemType;
typedef struct SeqList {
ElemType* data;
int length;
}SeqList;
//合并升序表A和降序表B到C,C为升序存储
//算法思想:依次取La,Lb中较小的元素插入Lc中,直到一条链元素全部元素全部插入Lc中,将另外一条链中元素依次插入Lc中,最后释放La,Lb存储空间
void combine(SeqList& La, SeqList& Lb, SeqList& Lc) {
int IndexLa = 0, IndexLb = Lb.length - 1, IndexLc = 0;
while (IndexLa < La.length && IndexLb>=0) {//依次取La,Lb中较小的元素插入Lc中
if (La.data[IndexLa] < Lb.data[IndexLb]) {
Lc.data[IndexLc++] = La.data[IndexLa++];
}
else {
Lc.data[IndexLc++] = Lb.data[IndexLb--];
}
}
if (IndexLa < La.length) {//La中有元素剩余,将La中剩余元素插入Lc中
while (IndexLa < La.length) {
Lc.data[IndexLc++] = La.data[IndexLa++];
}
}
else {//Lb中有元素剩余,将Lb中剩余元素插入Lc中
while (IndexLb >= 0) {
Lc.data[IndexLc++] = Lb.data[IndexLb--];
}
}
//释放La表和Lb表存储空间
free(La.data);
La.length = 0;
La.data = NULL;
free(Lb.data);
Lb.length = 0;
Lb.data = NULL;
}
int main()
{
SeqList La, Lb, Lc;
int m, n;
scanf("%d %d", &m, &n);
La.length = m;
Lb.length = n;
Lc.length = m + n;
La.data = (ElemType*)malloc(sizeof(ElemType) * m);
Lb.data = (ElemType*)malloc(sizeof(ElemType) * n);
Lc.data = (ElemType*)malloc(sizeof(ElemType) * (m + n));
//注意输入格式
for (int i = 0; i < La.length; i++) {
scanf("%d", &La.data[i]);
}
for (int i = 0; i < Lb.length; i++) {
scanf("%d", &Lb.data[i]);
}
combine(La, Lb, Lc);
for (int i = 0; i < Lc.length; i++) {
printf("%d ", Lc.data[i]);
}
}