python语言实现求两个单链表的差集源代码
时间: 2023-09-07 07:05:19 浏览: 101
实现求两个单链表的差集,即找出在第一个链表中出现但不在第二个链表中出现的元素。下面是Python语言的源代码实现:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
def getDifferenceList(head1, head2):
# 用两个集合分别存储链表1和链表2的元素
set1 = set()
set2 = set()
# 遍历链表1,将元素添加到集合set1中
p1 = head1
while p1:
set1.add(p1.value)
p1 = p1.next
# 遍历链表2,将元素添加到集合set2中
p2 = head2
while p2:
set2.add(p2.value)
p2 = p2.next
# 用集合操作求两个集合的差集
differenceSet = set1.difference(set2)
# 将差集转换成链表返回
differenceList = None
for value in differenceSet:
newNode = Node(value)
if not differenceList:
differenceList = newNode
else:
p = differenceList
while p.next:
p = p.next
p.next = newNode
return differenceList
```
以上代码的思路是先遍历链表,将链表中的元素分别添加到两个集合中,然后利用集合操作求两个集合的差集,最后将差集转换为链表返回。使用示例代码如下:
```python
# 创建链表1:1->2->3->4->5
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
head1.next.next.next = Node(4)
head1.next.next.next.next = Node(5)
# 创建链表2:3->4->6->7
head2 = Node(3)
head2.next = Node(4)
head2.next.next = Node(6)
head2.next.next.next = Node(7)
# 求差集
differenceList = getDifferenceList(head1, head2)
# 输出差集链表的元素:1 2 5
p = differenceList
while p:
print(p.value, end=' ')
p = p.next
```
输出结果为:1 2 5,表示在链表1中出现但不在链表2中出现的元素为1、2和5。
阅读全文