C++实现升序顺序表求并集
时间: 2023-05-29 07:05:23 浏览: 58
以下是C语言实现升序顺序表求并集的示例代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SqList;
void initList(SqList *list, int arr[], int size) {
for (int i = 0; i < size; i++) {
list->data[i] = arr[i];
}
list->length = size;
}
void printList(SqList list) {
printf("[");
for (int i = 0; i < list.length; i++) {
printf("%d", list.data[i]);
if (i != list.length - 1) {
printf(", ");
}
}
printf("]\n");
}
void unionList(SqList list1, SqList list2, SqList *list3) {
int i = 0, j = 0, k = 0;
while (i < list1.length && j < list2.length) {
if (list1.data[i] < list2.data[j]) {
list3->data[k++] = list1.data[i++];
} else if (list1.data[i] > list2.data[j]) {
list3->data[k++] = list2.data[j++];
} else {
list3->data[k++] = list1.data[i++];
j++;
}
}
while (i < list1.length) {
list3->data[k++] = list1.data[i++];
}
while (j < list2.length) {
list3->data[k++] = list2.data[j++];
}
list3->length = k;
}
int main() {
int arr1[] = {1, 3, 5, 7, 9};
int arr2[] = {2, 3, 4, 7, 8};
SqList list1, list2, list3;
initList(&list1, arr1, 5);
initList(&list2, arr2, 5);
unionList(list1, list2, &list3);
printf("List1: ");
printList(list1);
printf("List2: ");
printList(list2);
printf("Union List: ");
printList(list3);
return 0;
}
```
输出结果:
```
List1: [1, 3, 5, 7, 9]
List2: [2, 3, 4, 7, 8]
Union List: [1, 2, 3, 4, 5, 7, 8, 9]
```
阅读全文