建立两个有序递增的顺序表L1=(5,14, 17,21,23,31,56,70,81),L2=(6,10,17, 21,55,70),对L1和L2进行合并,要求合并后的顺序表仍有序递增且没有重复的元素值,输出合并后的顺序表。用C语言怎么实现
时间: 2023-06-08 11:05:20 浏览: 128
可以使用归并排序中的合并思想,将两个有序顺序表合并成一个有序顺序表。
C语言代码:
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int elem[MAXSIZE];
int length;
} SqList;
void merger(SqList L1, SqList L2, SqList *L3) {
int i = 0, j = 0, k = 0;
while (i < L1.length && j < L2.length) {
if (L1.elem[i] <= L2.elem[j]) {
if (L1.elem[i] != L3->elem[k-1]) {
L3->elem[k++] = L1.elem[i++];
} else {
i++;
}
} else {
if (L2.elem[j] != L3->elem[k-1]) {
L3->elem[k++] = L2.elem[j++];
} else {
j++;
}
}
}
while (i < L1.length) {
if (L1.elem[i] != L3->elem[k-1]) {
L3->elem[k++] = L1.elem[i++];
} else {
i++;
}
}
while (j < L2.length) {
if (L2.elem[j] != L3->elem[k-1]) {
L3->elem[k++] = L2.elem[j++];
} else {
j++;
}
}
L3->length = k;
}
int main() {
SqList L1 = {{5,14,17,21,23,31,56,70,81}, 9};
SqList L2 = {{6,10,17,21,55,70}, 6};
SqList L3;
for (int i = 0; i < MAXSIZE; i++) {
L3.elem[i] = 0;
}
merger(L1, L2, &L3);
printf("L3: ");
for (int i = 0; i < L3.length; i++) {
printf("%d ", L3.elem[i]);
}
printf("\n");
return 0;
}
阅读全文