7-3 两个有序链表序列的合并 用python
时间: 2023-05-22 15:06:05 浏览: 127
可以使用归并排序的思想来合并两个有序链表。
以下是 Python 代码示例:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# 创建一个哨兵结点
dummy = ListNode(0)
curr = dummy
# 遍历两个链表,比较每个结点的值
while l1 and l2:
if l1.val <= l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
# 将剩余的结点连接上
curr.next = l1 or l2
# 返回合并后的链表
return dummy.next
```
你也可以使用递归的方法来实现。
```python
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
```
希望能够帮到你!
阅读全文