难度:简单
描述:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路分析:
使用递归实现,新链表也不需要构造新节点,我们下面列举递归三个要素
- 终止条件:两条链表分别名为 l1 和 l2,当 l1 为空或 l2 为空时结束
- 返回值:每一层调用都返回排序好的链表头
- 本级递归内容:如果 l1 的 val 值更小,则将 l1.next 与排序好的链表头相接,l2 同理
代码实现:
var mergeTwoLists = function(l1, l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
let tempObj = {};
if (l1.val <= l2.val) {
tempObj = l1;
tempObj.next = mergeTwoLists(l1.next, l2);
} else {
tempObj = l2;
tempObj.next = mergeTwoLists(l2.next, l1);
}
return tempObj;
};
双指针
let mergeTwoLists = (l1, l2) => {
let head = new ListNode(), pre = head
while (l1 && l2) {
if(l1.val > l2.val){
pre.next = l2
l2 = l2.next
} else {
pre.next = l1
l1 = l1.next
}
pre = pre.next
}
pre.next = l1 ? l1 :l2
return head.next
};