用链表实现合并两个升序排序的整型数组(链表)为一个新的升序整型链表并输出
时间: 2024-06-16 14:08:29 浏览: 110
链表合并是一个经典的问题。假设我们有两个升序排序的链表 L1 和 L2,我们要将它们合并为一个新的升序链表 L3。
解决这个问题的一个简单方法是使用归并排序的思想。具体步骤如下:
1. 创建一个新的空链表 L3。
2. 比较 L1 和 L2 的头结点,将较小的节点加入到 L3 中,并将相应链表的头指针指向下一个节点。
3. 重复步骤 2 直到 L1 或 L2 中的一个为空。
4. 将非空链表的剩余节点加入到 L3 的末尾。
这里给出一个示例 Python 代码实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1:
cur.next = l1
else:
cur.next = l2
return dummy.next
```
阅读全文
相关推荐

















