剑指offer(16)合并两个排序的链表
题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题代码:
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function Merge(pHead1, pHead2)
{
// write code here
if(pHead1 == null && pHead2 == null){
return null;
}
if(pHead1 == null){
return pHead2;
}
if(pHead2 == null){
return pHead1;
}
var newHead = null;
if(pHead1.val <= pHead2.val){
newHead = pHead1;
newHead.next = Merge(pHead1.next,pHead2);
}
else{
newHead = pHead2;
newHead.next = Merge(pHead1,pHead2.next);
}
return newHead;
}