已知两个集合A和B,现要求A并B,如:A=(7,5,3,11),B=(2,6,3)合并后 A=(7,5,3,11,2,6) 用链表编程实现
时间: 2023-10-02 13:13:30 浏览: 63
c语言实现的链表集合的并集与交集.doc
以下是Python代码实现:
```python
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
return
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def __str__(self):
values = []
current_node = self.head
while current_node is not None:
values.append(str(current_node.value))
current_node = current_node.next
return "->".join(values)
def merge(A, B):
result = LinkedList()
current_node = A.head
while current_node is not None:
result.append(current_node.value)
current_node = current_node.next
current_node = B.head
while current_node is not None:
result.append(current_node.value)
current_node = current_node.next
return result
A = LinkedList()
A.append(7)
A.append(5)
A.append(3)
A.append(11)
B = LinkedList()
B.append(2)
B.append(6)
B.append(3)
merged = merge(A, B)
print(merged)
```
输出结果为:7->5->3->11->2->6->3
阅读全文