LeetCode21 合并两个有序链表 & 剑指Offer 25 合并两个排序的链表
题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3de81d49bc7bd502d89db23fee3a1407.png)
解题
解题一:迭代
var mergeTwoLists = function(l1, l2) {
const mergedHead = new ListNode(0);
let merged = mergedHead;
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
merged.next = l1;
l1 = l1.next;
} else {
merged.next = l2;
l2 = l2.next;
}
merged = merged.next;
}
merged.next = (l1 === null) ? l2 : l1;
return mergedHead.next;
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4d7490253ddbe0d24a63e888723016fb.png)
解题二:递归
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7fd2d1bde7d319ec5cab41d44072ba86.png)
var mergeTwoLists = function(l1, l2) {
if (l1 === null) return l2;
if (l2 === null) return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5d460b6f28918348c822586a1c85c760.png)