// 集合交运算 Set intersection(Set set1, Set set2) { Set set; init(&set); Node* p = set1.head; while (p != NULL) { if (strstr(set2.head, &(p->data)) != NULL) { insert(&set, p->data); } p = p->next; } return set; } // 集合并运算 Set union_set(Set set1, Set set2) { Set set; init(&set); Node* p = set1.head; while (p != NULL) { insert(&set, p->data); p = p->next; } p = set2.head; while (p != NULL) { if (strstr(set.head, &(p->data)) == NULL) { insert(&set, p->data); } p = p->next; } return set; } // 集合差运算 Set difference(Set set1, Set set2) { Set set; init(&set); Node* p = set1.head; while (p != NULL) { if (strstr(set2.head, &(p->data)) == NULL) { insert(&set, p->data); } p = p->next; } return set; }
时间: 2024-03-11 07:44:18 浏览: 28
这段代码实现了三个集合运算函数:交集、并集和差集。
intersection 函数用于求两个集合的交集,传入两个集合 set1 和 set2。它定义了一个新集合 set 并进行初始化。然后遍历 set1 集合中的每个节点,判断该节点的数据值是否也在 set2 集合中出现过,如果是则将该数据值插入到新集合 set 中。最后返回新集合 set。
union_set 函数用于求两个集合的并集,传入两个集合 set1 和 set2。它定义了一个新集合 set 并进行初始化。然后遍历 set1 集合中的每个节点,将每个节点的数据值插入到新集合 set 中。接着遍历 set2 集合中的每个节点,判断该节点的数据值是否已经在新集合 set 中出现过,如果没有则将该数据值插入到新集合 set 中。最后返回新集合 set。
difference 函数用于求两个集合的差集,传入两个集合 set1 和 set2,其中 set1 是被减集合,set2 是减集合。它定义了一个新集合 set 并进行初始化。然后遍历 set1 集合中的每个节点,判断该节点的数据值是否也在 set2 集合中出现过,如果不是则将该数据值插入到新集合 set 中。最后返回新集合 set。
需要注意的是,这些集合运算函数中使用了 C 语言标准库函数 strstr,用于在一个字符串中查找另一个字符串是否出现。这里将 set2.head 作为一个字符串,查找其中是否包含 p->data 这个字符。这种使用方法是错误的,因为 set2.head 只是一个指针,它并不是一个字符串。正确的做法应该是遍历 set2 集合,依次比较每个节点的数据值是否等于 p->data。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)