解题思路:
创建一个新的链表,然后双指针循环两个有序链表,值小的先合并,值相等都合并,然后再判断如果两个链表有没遍历完的,就直接合并到新链表,最后返回值
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
function mergeTwoLists (l1, l2) {
//1.创建头节点
var head = new ListNode(0)
var current = head;
//2.双指针循环遍历
while(l1 && l2) {
//2.1 值小的合并到新链表
if(l1.val < l2.val) {
current.next = new ListNode(l1.val);
current = current.next
l1 = l1.next
}else if (l1.val == l2.val) { //2.2 值相等都并入
current.next = new ListNode(l1.val);
current = current.next;
l1 = l1.next
current.next = new ListNode(l2.val);;
current = current.next;
l2 = l2.next;
}else {
current.next = new ListNode(l2.val);;
current = current.next;
l2 = l2.next;
}
// console.log(new ListNode())
}
//3.检查,没用遍历完的直接并入新链表
if(l1 != null){
current.next = l1
}
if(l2 != null){
current.next = l2
}
//4.返回head.next
return head.next
}
var l1 = {
val: 1,
next: {
val: 2,
next: {
val: 4,
next: null
}
}
}
var l2 = {
val: 1,
next: {
val: 3,
next: {
val: 5,
next: {
val: 6,
next: null
}
}
}
}
console.log(mergeTwoLists(l1, l2));
打印结果如下:
原文:https://www.cnblogs.com/lyt0207/p/12353126.html