python 链表并集
时间: 2023-08-29 20:03:08 浏览: 49
链表是一种常见的数据结构,Python提供了List作为链表的实现方式。链表并集指的是将两个链表中的所有元素合并到一个新的链表中,同时去除重复元素。
实现链表并集的一种简单的方法是创建一个新的链表,然后遍历两个链表,将元素逐个添加到新链表中。在添加元素之前,可以先判断该元素是否已经存在于新链表中,如果不存在则添加。
以下是Python代码示例:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_union(head1, head2):
# 创建一个新链表
union_head = None
union_tail = None
# 遍历链表1
current = head1
while current:
# 将链表1的元素添加到新链表中
if not union_head:
union_head = union_tail = Node(current.data)
else:
union_tail.next = Node(current.data)
union_tail = union_tail.next
current = current.next
# 遍历链表2
current = head2
while current:
# 判断链表2的元素是否已经存在于新链表中,如果不存在则添加
exists = False
temp = union_head
while temp:
if temp.data == current.data:
exists = True
break
temp = temp.next
if not exists:
union_tail.next = Node(current.data)
union_tail = union_tail.next
current = current.next
return union_head
# 创建链表1,例:1 -> 2 -> 3
head1 = Node(1)
head1.next = Node(2)
head1.next.next = Node(3)
# 创建链表2,例:2 -> 3 -> 4
head2 = Node(2)
head2.next = Node(3)
head2.next.next = Node(4)
union_head = get_union(head1, head2)
# 遍历输出链表并集
current = union_head
while current:
print(current.data)
current = current.next
```
以上代码实现了链表并集的功能,通过遍历两个链表,将元素逐个添加到新链表中。在添加元素之前,通过判断元素是否已经存在于新链表中,来去除重复元素。最后,遍历输出新链表即可得到两个链表的并集。