合并k个已排序链表

合并k个已排序的链表并将其作为一个已排序的链表返回。分析并描述其复杂度。

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param lists ListNode类一维数组 
 * @return ListNode类
 */
function mergeKLists( lists ) {
    // write code here
    var result = mergeTwoLists(lists[0],lists[1])
    if(lists.length>2){
        for(var i=2;i<lists.length;i++){
            result = mergeTwoLists(result,lists[i])
        }
    }
    return result
}

function mergeTwoLists( l1 ,  l2 ) {
    // write code here
    if(l1 == null) { return l2 }
    if(l2 == null) { return l1 }
    var head={}
    var current = head
    while(l1&&l2){
        if(l1.val<l2.val){
            current.next = l1
            current = current.next
            l1 = l1.next
        }else{
            current.next = l2
            current = current.next
            l2 = l2.next
        }
    }
    while(l1){
        current.next =l1
        current = current.next
        l1=l1.next
    }
    while(l2){
        current.next =l2
        current = current.next
        l2=l2.next
    }
    return head.next
}
module.exports = {
    mergeTwoLists : mergeTwoLists,
    mergeKLists : mergeKLists
};
链表算法 文章被收录于专栏

链表相关算法

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
测试糕手手:社会第一课,随便吹牛逼,直接说四个月,别老实。老实人只会被欺负
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务