假设利用线性表分别表示两个集合A和B(即线性表中的数据元素即为集合中的成员),现要求基于线性表的顺序存储结构编制程序实现整数集合的并、交、差运算,即求三个新的集合,分别表示 C = A ∪ B, D = A ∩ B, E = A - B。(C语言代码)
时间: 2024-06-17 13:07:27 浏览: 12
可以基于线性表的顺序存储结构来实现整数集合的并、交、差运算,具体代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
void InitList(SqList *L) {
L->length = 0;
}
void InputSet(SqList *L) {
int n, i, x;
printf("请输入集合元素个数:");
scanf("%d", &n);
printf("请输入集合元素:");
for (i = 0; i < n; i++) {
scanf("%d", &x);
L->data[i] = x;
}
L->length = n;
}
void PrintSet(SqList L) {
int i;
printf("{");
for (i = 0; i < L.length; i++) {
printf("%d", L.data[i]);
if (i < L.length - 1) {
printf(",");
}
}
printf("}\n");
}
void Union(SqList A, SqList B, SqList *C) {
int i, j, k;
InitList(C);
for (i = 0; i < A.length; i++) {
C->data[i] = A.data[i];
C->length++;
}
for (j = 0; j < B.length; j++) {
for (k = 0; k < A.length; k++) {
if (B.data[j] == A.data[k]) {
break;
}
}
if (k >= A.length) {
C->data[C->length++] = B.data[j];
}
}
}
void Intersect(SqList A, SqList B, SqList *D) {
int i, j, k;
InitList(D);
for (i = 0; i < A.length; i++) {
for (j = 0; j < B.length; j++) {
if (A.data[i] == B.data[j]) {
D->data[D->length++] = A.data[i];
break;
}
}
}
}
void Difference(SqList A, SqList B, SqList *E) {
int i, j, k;
InitList(E);
for (i = 0; i < A.length; i++) {
for (j = 0; j < B.length; j++) {
if (A.data[i] == B.data[j]) {
break;
}
}
if (j >= B.length) {
E->data[E->length++] = A.data[i];
}
}
}
int main() {
SqList A, B, C, D, E;
printf("请输入集合A:\n");
InputSet(&A);
printf("集合A = ");
PrintSet(A);
printf("请输入集合B:\n");
InputSet(&B);
printf("集合B = ");
PrintSet(B);
Union(A, B, &C);
printf("A ∪ B = ");
PrintSet(C);
Intersect(A, B, &D);
printf("A ∩ B = ");
PrintSet(D);
Difference(A, B, &E);
printf("A - B = ");
PrintSet(E);
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)