用python写出:有两个带附加头结点的单链表,结点包含两个域:entry和next,若单链表中的元素值递增有序排列,请写算法,将两个单链表按顺序合并成一个链表。
时间: 2023-06-01 07:01:34 浏览: 67
```
class Node:
def __init__(self, entry=None, next=None):
self.entry = entry
self.next = next
class LinkedList:
def __init__(self):
self.head = Node()
def add(self, entry):
new_node = Node(entry)
current = self.head
while current.next and current.next.entry < entry:
current = current.next
new_node.next = current.next
current.next = new_node
def merge(self, other):
current1 = self.head.next
current2 = other.head.next
merged_list = LinkedList()
while current1 and current2:
if current1.entry < current2.entry:
merged_list.add(current1.entry)
current1 = current1.next
else:
merged_list.add(current2.entry)
current2 = current2.next
while current1:
merged_list.add(current1.entry)
current1 = current1.next
while current2:
merged_list.add(current2.entry)
current2 = current2.next
return merged_list
```
使用方法:
```
list1 = LinkedList()
list1.add(1)
list1.add(3)
list1.add(5)
list2 = LinkedList()
list2.add(2)
list2.add(4)
list2.add(6)
merged_list = list1.merge(list2)
current = merged_list.head.next
while current:
print(current.entry)
current = current.next
```
输出结果:
```
1
2
3
4
5
6
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)