题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

要想合并链表,基本思路就是要判断谁在谁的后面, 假设第一链表节点pHead1小于第二链表节点pHead2,那么pHead2肯定在pHead1后面,但未必就是它的next,因为next可能小于pHead2,因此需要进一步判断,使用递归。因为两个链表是递增的,因此当一个链表已经遍历完了,后面的链表无需操作,直接链接即可。

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param pHead1 ListNode类
 * @param pHead2 ListNode类
 * @return ListNode类
 */
function Merge(pHead1, pHead2) {
    // write code here
    // 当另其中一个链表已经结束,因为是递增的,后续接上另一个链表结束
    if(pHead1==null) return pHead2
    if(pHead2==null) return pHead1
    if (pHead1.val < pHead2.val) {
        // 谁小谁在后面,但第二个链表head未必就比第一个链表head的next小
        // pHead1.next = pHead2
        // 因此,还需要判断第一个链表head的next和第二个链表head进一步比较
        pHead1.next = Merge(pHead1.next,pHead2)
        return pHead1
    } else {
        pHead2.next = Merge(pHead2.next,pHead1)
        return pHead2
    }
}
module.exports = {
    Merge: Merge,
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务