C语言编程,用两种方法,用最简单的方法求:集合A、B的差集,由所有属于A但不属于B的元素构成,输出A、B的差集,以空格分隔,-1表示输入结束
时间: 2024-02-22 12:55:00 浏览: 25
除了使用两个数组的方法之外,还可以使用链表的方法来求集合的差集。具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList() {
Node *head = NULL;
Node *tail = NULL;
int x;
while (1) {
scanf("%d", &x);
if (x == -1) break;
Node *node = (Node *)malloc(sizeof(Node));
node->data = x;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
void printList(Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("-1\n");
}
Node *setDifference(Node *A, Node *B) {
Node *head = NULL;
Node *tail = NULL;
while (A != NULL) {
int found = 0;
Node *p = B;
while (p != NULL) {
if (A->data == p->data) {
found = 1;
break;
}
p = p->next;
}
if (!found) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = A->data;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
A = A->next;
}
return head;
}
int main() {
Node *A = createList();
Node *B = createList();
Node *diff = setDifference(A, B);
printList(diff);
return 0;
}
```
其中,`createList()` 函数用于创建链表,`printList()` 函数用于输出链表中的元素,`setDifference()` 函数用于求两个集合的差集。在 `setDifference()` 函数中,我们遍历链表 A 的每个元素,判断是否也在链表 B 中出现,如果不出现则将该元素添加到差集链表中。最后,输出差集链表中的元素即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![C](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)