用C语言实现利用顺序表完成创建两个集合并且求集合的交集和并集以及输出
时间: 2023-05-26 08:06:58 浏览: 115
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct set {
int data[MAXSIZE];
int length;
} Set;
void initSet(Set *s) {
s->length = 0;
}
void addToSet(Set *s, int x) {
if (s->length >= MAXSIZE) {
printf("Set is full!\n");
return;
}
for (int i = 0; i < s->length; i++) {
if (s->data[i] == x) {
return;
}
}
s->data[s->length] = x;
s->length++;
}
void createSet(Set *s) {
int n, x;
printf("Please enter the size of the set: ");
scanf("%d", &n);
printf("Please enter the elements of the set: ");
for (int i = 0; i < n; i++) {
scanf("%d", &x);
addToSet(s, x);
}
}
void printSet(Set s) {
printf("{");
for (int i = 0; i < s.length; i++) {
printf("%d", s.data[i]);
if (i < s.length - 1) {
printf(", ");
}
}
printf("}\n");
}
Set intersection(Set s1, Set s2) {
Set result;
initSet(&result);
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s1.data[i] == s2.data[j]) {
addToSet(&result, s1.data[i]);
break;
}
}
}
return result;
}
Set unionSet(Set s1, Set s2) {
Set result;
initSet(&result);
for (int i = 0; i < s1.length; i++) {
addToSet(&result, s1.data[i]);
}
for (int i = 0; i < s2.length; i++) {
addToSet(&result, s2.data[i]);
}
return result;
}
int main() {
Set s1, s2;
createSet(&s1);
createSet(&s2);
printf("Set 1: ");
printSet(s1);
printf("Set 2: ");
printSet(s2);
Set s_intersection = intersection(s1, s2);
printf("Intersection: ");
printSet(s_intersection);
Set s_union = unionSet(s1, s2);
printf("Union: ");
printSet(s_union);
return 0;
}
```
阅读全文