21. 合并两个有序链表 / 剑指 Offer 25. 合并两个排序的链表
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
}
迭代法:
var mergeTwoLists = function(l1, l2) {
// 定义头结点,确保链表可以被访问到
let head = new ListNode()
let cur = head
while(l1 && l2) {
// 如果l1的结点值较小
if(l1.val<=l2.val) {
// 先串起l1的结点
cur.next = l1
// l1指针向前一步
l1 = l1.next
} else {
cur.next = l2
l2 = l2.next
}
// 在串起一个结点后,也会往前一步
cur = cur.next
}
//处理链表不等长的情况
cur.next = l1!==null?l1:l2
//返回起始结点
return head.next
}
递归法:
var mergeTwoLists = function(l1, l2) {
if(l1==null){
return l2
}else if(l2==null){
return l1
}else if(l1.val<l2.val){
l1.next=mergeTwoLists(l1.next,l2)
return l1
}else{
l2.next=mergeTwoLists(l1,l2.next)
return l2
}
}
1669. 合并两个链表
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {number} a
* @param {number} b
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeInBetween = function(list1, a, b, list2) {
};
迭代法: 循环遍历
var mergeInBetween = function(list1, a, b, list2) {
let curr=list1;
// 遍历到a前一个节点 使curr指向a-1节点
for(let i=0;i<a-1;i++){
curr=curr.next;
}
// 让node指向curr.next 进行遍历 到b的下一个节点 使node指向b+1节点
let node=curr.next;
for(let i=a;i<b+1;i++){
node=node.next;
}
//从b+1位置开始 插入list2 使curr.next指向list2
curr.next=list2;
while(curr.next){
curr=curr.next;
}
// lis2全部插入后 过滤list1后所有节点 将curr.next指向node
curr.next=node;
return list1;
};
23. 合并K个升序链表
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
}
迭代法:
解题思路:将所有节点push取出 并sort排序 再统一存
var mergeKLists = function(lists) {
const list=[];
for(let i=0;i<lists.length;i++){
let node=lists[i];
while(node){
list.push(node.val);
node=node.next;
}
}
list.sort((a,b)=>a-b);
let res=new ListNode(0);
let cur=res;
for(let i=0;i<list.length;i++){
cur.next=new ListNode(list[i]);
cur=cur.next;
}
return res.next;
}
递归法:
var mergeKLists = function(lists) {
if (!lists.length) return null
//递归出口,即数组中只剩一条链表时,合并完毕
if (lists.length === 1) return lists[0]
//两个一组的合并,合并完了更新数组(每次合并前两个)
lists.splice(0, 2, mergeTwoLists(lists[0], lists[1]))
//递归
return mergeKLists(lists)
//尾插法合并两个链表
function 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
};
}