用有序单链表表示集合,实现集合的交、并、差运算
时间: 2024-02-01 09:03:43 浏览: 77
以下是用Python语言实现集合交、并、差运算的示例代码,其中假设链表中的元素为整数:
```python
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class Set:
def __init__(self):
self.head = None
# 在集合中添加元素
def add(self, val):
if not self.contains(val):
new_node = Node(val)
new_node.next = self.head
self.head = new_node
# 判断集合中是否包含某个元素
def contains(self, val):
curr = self.head
while curr:
if curr.val == val:
return True
curr = curr.next
return False
# 集合的交运算
def intersection(self, other):
result = Set()
curr = self.head
while curr:
if other.contains(curr.val):
result.add(curr.val)
curr = curr.next
return result
# 集合的并运算
def union(self, other):
result = Set()
curr = self.head
while curr:
result.add(curr.val)
curr = curr.next
curr = other.head
while curr:
result.add(curr.val)
curr = curr.next
return result
# 集合的差运算
def difference(self, other):
result = Set()
curr = self.head
while curr:
if not other.contains(curr.val):
result.add(curr.val)
curr = curr.next
return result
```
使用示例:
```python
# 创建两个集合
set1 = Set()
set2 = Set()
# 添加元素
set1.add(1)
set1.add(2)
set1.add(3)
set2.add(3)
set2.add(4)
set2.add(5)
# 集合的交运算
result = set1.intersection(set2)
curr = result.head
while curr:
print(curr.val)
curr = curr.next
# 输出:3
# 集合的并运算
result = set1.union(set2)
curr = result.head
while curr:
print(curr.val)
curr = curr.next
# 输出:1 2 3 4 5
# 集合的差运算
result = set1.difference(set2)
curr = result.head
while curr:
print(curr.val)
curr = curr.next
# 输出:1 2
```
阅读全文