1. 题目
【剑指offer】BM4 合并两个排序的链表
2. 代码
- 方法一:递归
function Merge(pHead1, pHead2)
{
if(pHead1 === null) return pHead2
if(pHead2 === null) return pHead1
while(pHead1 !== null && pHead2 !== null) {
if(pHead1.val <= pHead2.val) {
pHead1.next = Merge(pHead1.next, pHead2)
return pHead1
} else if(pHead2.val < pHead1.val) {
pHead2.next = Merge(pHead1, pHead2.next)
return pHead2
}
}
}
module.exports = {
Merge : Merge
};
- 方法二:创建一个新链表,每次比较都向新链表上挂载节点。
function Merge(pHead1, pHead2)
{
if(pHead1 == null) return pHead2
if(pHead2 == null) return pHead1
if(pHead1 == null && pHead2 == null) return null
let res = {
val: null,
next:null,
}
let cur = res
while(pHead1 != null && pHead2 != null) {
if(pHead1.val < pHead2.val) {
cur.next = pHead1
pHead1 = pHead1.next
} else {
cur.next = pHead2
pHead2 = pHead2.next
}
cur = cur.next
}
if(pHead1 != null) cur.next = pHead1
else if(pHead2 != null) cur.next = pHead2
return res.next
}
module.exports = {
Merge : Merge
};
3. 参考
- 一看就会,一写就废?详解递归