题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路分析
用递归思想,依次将两个链表的每个元素递归对比后实现,注意此题考查代码的鲁棒性,故判断条件不能少!
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function Merge(pHead1, pHead2)
{
if(pHead1 == null) {
return pHead2;
}else if(pHead2 == null) {
return pHead1;
}
var result = {};
if(pHead1.val < pHead2.val) {
result = pHead1;
result.next = Merge(pHead1.next, pHead2);
}else {
result = pHead2;
result.next = Merge(pHead1, pHead2.next);
}
return result;
}
function Merge(pHead1, pHead2)
{
// write code here
var head=new ListNode(0);
var pHead=head;
while(pHead1!=null && pHead2!=null){
if(pHead1.val>=pHead2.val){
head.next=pHead2;
pHead2=pHead2.next;
}else{
head.next=pHead1;
pHead1=pHead1.next;
}
head=head.next;
}
if(pHead1!=null){
head.next=pHead1;
}
if(pHead2!=null){
head.next=pHead2;
}
return pHead.next;
}