描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
示例1
输入:
{1,3,5},{2,4,6}
返回值:
{1,2,3,4,5,6}
代码
非递归做法
function ListNode(x){
this.val = x;
this.next = null;
}
function Merge(pHead1, pHead2)
{
// write code here
let p=new ListNode(0)
const root=p
while(pHead1&&pHead2){
if(pHead1.val>pHead2.val){
p.next=pHead2
p=p.next
pHead2=pHead2.next
}else{
p.next=pHead1
p=p.next
pHead1=pHead1.next
}
}
if(pHead1){
p.next=pHead1
}else{
p.next=pHead2
}
return root.next
}
module.exports = {
Merge : Merge
};
递归做法
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function Merge(pHead1, pHead2)
{
// write code here
if(!pHead1) return pHead2
if(!pHead2) return pHead1
if(pHead1.val<pHead2.val){
pHead1.next=Merge(pHead1.next, pHead2)
return pHead1
}else{
pHead2.next=Merge(pHead1, pHead2.next)
return pHead2
}
}
module.exports = {
Merge : Merge
};