写一个用链表和c语言写的计算集合A和集合B的交集、并集、差集以及集合A对全集的补集和集合B对全集的补集补集的代码,要求手动输入集合A、集合B以及全集,并在相应步骤上加上注释
时间: 2024-03-20 08:44:12 浏览: 52
好的,以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
typedef struct node node;
/*创建链表*/
node* createList() {
node* head = (node*)malloc(sizeof(node));
head->next = NULL;
return head;
}
/*插入节点*/
void insert(node* head, int data) {
node* p = head;
while (p->next != NULL) {
p = p->next;
}
node* new_node = (node*)malloc(sizeof(node));
new_node->data = data;
new_node->next = NULL;
p->next = new_node;
}
/*计算并集*/
node* unionSet(node* setA, node* setB) {
node* setU = createList();
node* p = setA->next;
while (p != NULL) {
insert(setU, p->data);
p = p->next;
}
p = setB->next;
while (p != NULL) {
if (!contains(setU, p->data)) {
insert(setU, p->data);
}
p = p->next;
}
return setU;
}
/*计算交集*/
node* intersection(node* setA, node* setB) {
node* setI = createList();
node* p = setA->next;
while (p != NULL) {
if (contains(setB, p->data)) {
insert(setI, p->data);
}
p = p->next;
}
return setI;
}
/*计算差集*/
node* difference(node* setA, node* setB) {
node* setD = createList();
node* p = setA->next;
while (p != NULL) {
if (!contains(setB, p->data)) {
insert(setD, p->data);
}
p = p->next;
}
return setD;
}
/*判断元素是否在集合中*/
int contains(node* set, int data) {
node* p = set->next;
while (p != NULL) {
if (p->data == data) {
return 1;
}
p = p->next;
}
return 0;
}
/*计算补集*/
node* complement(node* set, node* universe) {
node* setC = createList();
node* p = universe->next;
while (p != NULL) {
if (!contains(set, p->data)) {
insert(setC, p->data);
}
p = p->next;
}
return setC;
}
/*输出集合*/
void printSet(node* set) {
printf("{ ");
node* p = set->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("}\n");
}
int main() {
/*手动输入集合A、集合B以及全集*/
node* setA = createList();
node* setB = createList();
node* universe = createList();
int num;
printf("请输入集合A,以-1结束:\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
insert(setA, num);
}
printf("请输入集合B,以-1结束:\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
insert(setB, num);
}
printf("请输入全集,以-1结束:\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
insert(universe, num);
}
/*计算并集、交集、差集、补集*/
node* setU = unionSet(setA, setB);
node* setI = intersection(setA, setB);
node* setD = difference(setA, setB);
node* setAc = complement(setA, universe);
node* setBc = complement(setB, universe);
/*输出结果*/
printf("集合A:");
printSet(setA);
printf("集合B:");
printSet(setB);
printf("全集:");
printSet(universe);
printf("并集:");
printSet(setU);
printf("交集:");
printSet(setI);
printf("差集(A-B):");
printSet(setD);
printf("集合A的补集:");
printSet(setAc);
printf("集合B的补集:");
printSet(setBc);
/*释放内存*/
free(setA);
free(setB);
free(universe);
free(setU);
free(setI);
free(setD);
free(setAc);
free(setBc);
return 0;
}
```
注:上述代码实现了用链表和 C 语言计算集合的交集、并集、差集以及补集,代码中包括注释,可以更好地理解代码的实现过程。
阅读全文