题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例一:输入:,
输出:
示例二:
输入:,
输出:
示例三:
输入:,
输出:
提示:
- 两个链表的节点范围是
- 和均按非递减顺序排列
解题
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1, l2):
# 创建一个虚拟头节点
dummy = ListNode()
current = dummy
# 遍历两个链表,直到其中一个为空
while l1 and l2:
if l1.val <= l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
# 连接剩余的节点
if l1:
current.next = l1
else:
current.next = l2
# 返回合并后的链表,跳过虚拟头节点
return dummy.next
# 示例用法
# 创建链表1 -> 2 -> 4
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
# 创建链表1 -> 3 -> 4
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
# 合并链表
merged_list = mergeTwoLists(l1, l2)
# 打印合并后的链表
current = merged_list
while current:
print(current.val, end=" -> ")
current = current.next
1 -> 1 -> 2 -> 3 -> 4 -> 4 ->
总结
- 使用虚拟头节点简化操作,避免处理复杂的边界情况。
- 在合并时,维护链表的升序属性,确保结果链表也是升序的。