编写一个能完成集合交,并和差的程序,而且分别用数组和单向链表表示集合
时间: 2023-04-09 16:00:28 浏览: 82
好的,这是一个关于编程的问题,我可以回答。以下是使用数组和单向链表表示集合的交并差的程序:
使用数组表示集合:
```python
def intersection(a, b):
return list(set(a) & set(b))
def union(a, b):
return list(set(a) | set(b))
def difference(a, b):
return list(set(a) - set(b))
```
使用单向链表表示集合:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def to_list(self):
result = []
current = self.head
while current is not None:
result.append(current.data)
current = current.next
return result
def intersection(a, b):
set_a = set(a.to_list())
set_b = set(b.to_list())
result = set_a & set_b
linked_list = LinkedList()
for item in result:
linked_list.add(item)
return linked_list
def union(a, b):
set_a = set(a.to_list())
set_b = set(b.to_list())
result = set_a | set_b
linked_list = LinkedList()
for item in result:
linked_list.add(item)
return linked_list
def difference(a, b):
set_a = set(a.to_list())
set_b = set(b.to_list())
result = set_a - set_b
linked_list = LinkedList()
for item in result:
linked_list.add(item)
return linked_list
```
希望这个程序能够帮到您!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)