合并两个排序的链表

问题:

输入两个单调递增的链表,输出两个链表合成后的链表,需要合成后的链表满足单调不减规则。

利用递归的方法解决该问题。

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function Merge(pHead1, pHead2)
{
    // write code here
    let pHead = new ListNode();
    if(pHead1==null){
        return pHead2;
    }else if(pHead2==null){
        return pHead1;
    }
    if(pHead1.val<=pHead2.val){
        pHead = pHead1;
        pHead.next = Merge(pHead1.next,pHead2);
    }else{
        pHead = pHead2;
        pHead.next = Merge(pHead1,pHead2.next);
    }
    return pHead;
}

需要注意代码的鲁棒性:

当输入为空指针时,程序会因为试图访问空指针指向的内容而崩溃。

posted @ 2019-06-16 17:06  湛蓝的家  阅读(162)  评论(0编辑  收藏  举报