已知两个集合A和B,现要求A并B,如:A=(7,5,3,11),B=(2,6,3)合并后 A=(7,5,3,11,2,6) 用链表编程实现
时间: 2023-10-08 11:05:38 浏览: 20
好的,这个问题我可以回答。以下是链表实现的代码:
class Node:
def __init__(self, value):
self.value = value
self.next = None
def merge_lists(list1, list2):
if not list1:
return list2
if not list2:
return list1
current_node = list1
while current_node.next:
current_node = current_node.next
current_node.next = list2
return list1
# test
list1 = Node(7)
list1.next = Node(5)
list1.next.next = Node(3)
list1.next.next.next = Node(11)
list2 = Node(2)
list2.next = Node(6)
list2.next.next = Node(3)
merged_list = merge_lists(list1, list2)
current_node = merged_list
while current_node:
print(current_node.value)
current_node = current_node.next
# Output: 7 5 3 11 2 6 3