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

合并k个已排序的链表

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

#include <stdio.h>
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    struct ListNode* head = NULL;
    struct ListNode* tmp = NULL;
    if (pHead1 == NULL) {
        return pHead2;
    }
    if (pHead2 == NULL) {
        return pHead1;
    }
    if (pHead1->val < pHead2->val) {
        head = pHead1;
        pHead1 = pHead1->next;
    } else {
        head = pHead2;
        pHead2 = pHead2->next;
    }
    tmp = head;


    while (tmp) {
        if (pHead1 == NULL) {
            tmp->next = pHead2;
            break;
        }
        if (pHead2 == NULL) {
            tmp->next = pHead1;
            break;
        }
        if (pHead1->val < pHead2->val) {
            tmp->next = pHead1;
            pHead1 = pHead1->next;
        } else {
            tmp->next = pHead2;
            pHead2 = pHead2->next;
        }
        tmp = tmp->next;
    }
    return head;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
    
    int index = 0;
    struct ListNode* head = NULL;
    if(listsLen==1)
    {
        return lists[0];
    }
    for(index=0;index<listsLen;index++)
    {
        head = Merge(head, lists[index]);
    }
    return head;
}

全部评论

相关推荐

10-05 23:02
东北大学 Java
我说句实话啊:那时候看三个月培训班视频,随便做个项目背点八股,都能说3 40w是侮辱价
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务