6-2 两个有序链表序列的合并
时间: 2024-06-10 13:04:03 浏览: 122
两个有序链表的合并
合并两个有序链表的方法如下所示:
```python
def mergeTwoLists(l1, l2):
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 if l1 else l2
return dummy.next
```
阅读全文