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

合并k个已排序的链表

http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

使用归并思想

static struct ListNode * merge(struct ListNode * h1,struct ListNode * h2){
    struct ListNode * C = NULL;
    if(h1 == NULL || h2 == NULL){
        if(h1 == NULL){
            return h2;
        }else{
            return h1;
        }
    }
    if(h1->val < h2->val){
        C = h1;
        h1 = h1->next;
    }else{
        C  = h2;
        h2 = h2->next;
    }
    struct ListNode * work = C;
    while( h1 != NULL && h2 != NULL){
        if( h1->val < h2->val){
            work->next = h1;
            work = work->next;
            h1 = h1->next;
        }else{
            work->next = h2;
            work = work->next;
            h2 = h2->next;
        }
    }
    if(h1 == NULL){
        work->next = h2;
    }else{
        work->next = h1;
    }
    return C;
}
static struct ListNode * mergeLists(struct ListNode * lists[],int start,int end){
    if(start == end){
        return lists[start];
    }else{
        
        int mid = ( start + end ) / 2;
        struct ListNode * h1 = mergeLists(lists,start,mid);
        struct ListNode * h2 = mergeLists(lists,mid+1,end);
        return merge(h1,h2);
        
    }
}

struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
    // write code here
    if(listsLen == 0){
        return NULL;
    }
    return mergeLists(lists,0,listsLen-1);
}
全部评论

相关推荐

joe2333:怀念以前大家拿华为当保底的日子
点赞 评论 收藏
分享
美团 后端开发 总包n(15%是股票)
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务