用C语言实现集合的创建,并集,交集,输出
时间: 2023-05-29 15:01:39 浏览: 395
C语言中创建一个list
以下是使用C语言实现集合的创建、并集、交集和输出的示例代码:
```c
#include <stdio.h>
#define MAX_SIZE 10
typedef struct _set {
int elements[MAX_SIZE];
int size;
} Set;
void createSet(Set *set, int *arr, int size) {
set->size = size;
for (int i = 0; i < size; i++) {
set->elements[i] = arr[i];
}
}
Set unionSet(Set set1, Set set2) {
Set result;
int i = 0, j = 0, k = 0;
while (i < set1.size && j < set2.size) {
if (set1.elements[i] < set2.elements[j]) {
result.elements[k++] = set1.elements[i++];
} else if (set1.elements[i] > set2.elements[j]) {
result.elements[k++] = set2.elements[j++];
} else {
result.elements[k++] = set1.elements[i++];
j++;
}
}
while (i < set1.size) {
result.elements[k++] = set1.elements[i++];
}
while (j < set2.size) {
result.elements[k++] = set2.elements[j++];
}
result.size = k;
return result;
}
Set intersectSet(Set set1, Set set2) {
Set result;
int i = 0, j = 0, k = 0;
while (i < set1.size && j < set2.size) {
if (set1.elements[i] < set2.elements[j]) {
i++;
} else if (set1.elements[i] > set2.elements[j]) {
j++;
} else {
result.elements[k++] = set1.elements[i++];
j++;
}
}
result.size = k;
return result;
}
void printSet(Set set) {
printf("{ ");
for (int i = 0; i < set.size; i++) {
printf("%d ", set.elements[i]);
}
printf("}\n");
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 4, 5, 6, 7};
Set set1, set2, set_union, set_intersect;
createSet(&set1, arr1, sizeof(arr1) / sizeof(int));
createSet(&set2, arr2, sizeof(arr2) / sizeof(int));
printf("Set 1: ");
printSet(set1);
printf("Set 2: ");
printSet(set2);
set_union = unionSet(set1, set2);
printf("Set union: ");
printSet(set_union);
set_intersect = intersectSet(set1, set2);
printf("Set intersect: ");
printSet(set_intersect);
return 0;
}
```
输出:
```
Set 1: { 1 2 3 4 5 }
Set 2: { 3 4 5 6 7 }
Set union: { 1 2 3 4 5 6 7 }
Set intersect: { 3 4 5 }
```
阅读全文