输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围: 0≤𝑛≤1000,−1000≤节点值≤1000
要求:空间复杂度 O(1),时间复杂度 O(n)
示例转换:
C++核心代码实现
public class Solution {
public ListNode Merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(-1); // 创建虚拟头节点,值为 -1(值无所谓,只是个占位)
ListNode current = dummy; // current 初始指向 dummy 节点
while (head1 != null && head2 != null) { // 当两个链表都不为空时
if (head1.val <= head2.val) { // 比较 head1 和 head2 的值
current.next = head1; // 将较小的 head1 节点连接到 current 后面
head1 = head1.next; // 移动 head1 指针
} else {
current.next = head2; // 将较小的 head2 节点连接到 current 后面
head2 = head2.next; // 移动 head2 指针
}
current = current.next; // 移动 current 指针
}
// 处理剩余的节点
if (head1 != null) {
current.next = head1; // 如果 head1 不为空,将其全部连接到 current 后面
}
if (head2 != null) {
current.next = head2; // 如果 head2 不为空,将其全部连接到 current 后面
}
return dummy.next; // 返回合并后的链表的头节点,跳过虚拟头节点 dummy
}
}
Python核心代码实现
class Solution:
def Merge(self, pHead1: ListNode, pHead2: ListNode) -> ListNode:
# 创建一个虚拟头节点
dummy = ListNode(0)
current = dummy
# 逐个比较两个链表的节点值,选择较小的节点连接到新链表
while pHead1 and pHead2:
if pHead1.val <= pHead2.val:
current.next = pHead1
pHead1 = pHead1.next
else:
current.next = pHead2
pHead2 = pHead2.next
current = current.next
# 将剩余的节点连接到新链表
if pHead1:
current.next = pHead1
if pHead2:
current.next = pHead2
# 返回合并后的链表头节点(跳过虚拟头节点)
return dummy.next