已知2个按元素值递增有序顺序表La,Lb,设计一个算法将2个表的全部元素归并为一个按元素值递增有序的顺序表Lc。用C++写
时间: 2024-05-13 10:20:37 浏览: 103
```c
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef struct {
int elem[MAXSIZE];
int length;
} SqList;
void InitList(SqList *L) {
L->length = 0;
}
void InputList(SqList *L) {
printf("请输入元素个数:");
scanf("%d", &(L->length));
printf("请输入元素:");
for(int i=0; i<L->length; i++) {
scanf("%d", &(L->elem[i]));
}
}
void MergeList(SqList La, SqList Lb, SqList *Lc) {
int i = 0, j = 0, k = 0;
while(i < La.length && j < Lb.length) {
if(La.elem[i] <= Lb.elem[j]) {
Lc->elem[k++] = La.elem[i++];
}
else {
Lc->elem[k++] = Lb.elem[j++];
}
}
while(i < La.length) {
Lc->elem[k++] = La.elem[i++];
}
while(j < Lb.length) {
Lc->elem[k++] = Lb.elem[j++];
}
Lc->length = k;
}
void PrintList(SqList L) {
for(int i=0; i<L.length; i++) {
printf("%d ", L.elem[i]);
}
printf("\n");
}
int main() {
SqList La, Lb, Lc;
InitList(&La);
InitList(&Lb);
InputList(&La);
InputList(&Lb);
MergeList(La, Lb, &Lc);
printf("归并后的顺序表Lc为:");
PrintList(Lc);
return 0;
}
```
阅读全文