一、题目描述
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
输入:list1 = 1 -> 3 -> 5,list2 = 2 -> 4 -> 6
输出:1 -> 2 -> 3 -> 4 -> 5 -> 6
二、解决思路
合并有序链表的核心思路在于双指针遍历和比较,具体分为两种方法:迭代法和递归法。
迭代法
- 核心思想:
使用两个指针分别遍历两个链表,每次选择较小的节点加入新链表,直到某个链表遍历完毕,再将剩余节点链接到末尾。 - 步骤分解:
-
创建头节点 :
作为新链表的起始占位符。 -
初始化指针:
curr指向头节点,p1和p2分别指向list1和list2的头节点。 -
比较与链接:
循环比较p1.val和p2.val,将较小的节点链接到curr.next,并移动对应指针。 -
处理剩余节点:
当某个链表遍历完毕时,将另一链表的剩余节点直接链接到末尾。 -
返回结果:
头节点的next即为合并后的头节点。
-
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
if (!list1 && list2) {
return list2;
} else if (list1 && !list2) {
return list1;
}
let head = new ListNode(), p3 = head;
while (list1 && list2) {
if (list1.val <= list2.val) {
p3.next = list2;
list2 = list2.next;
} else {
p3.next = list1;
list1 = list1.next;
}
p3 = p3.next;
}
p3.next = list1 ? list1 : list2;
return head.next;
};