LeetCode:023.合并K个有序链表

      起初自己在做这道习题的时候,并没有通过,自己的错误在于没有考虑链表可能为空的情况,所以参考并且学习其他人的代码,发现自己的错误在于没有注意一些边界情况,所以导致只有编译通过,但是真正提交测试的时候出错。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(l1==NULL)
    {
        return l2;
    }
    if(l2==NULL)
    {
        return l1;
    }
    if(l1->val<=l2->val)
    {
        l1->next=mergeTwoLists(l1->next,l2); 
        return l1;
    }
    else
    {
        l2->next=mergeTwoLists(l2->next,l1);
        return l2;
    }
}

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
    //遍历一次链表对所有两个链表执行一次上述函数
    if(lists==NULL||listsSize==0)
    {
        return NULL;
    }
    struct ListNode* res=lists[0];
    for(int i=1;i<listsSize;i++)
    {
      
            res=mergeTwoLists(res,lists[i]);
    }
    return res;
}
发布了69 篇原创文章 · 获赞 33 · 访问量 1186

猜你喜欢

转载自blog.csdn.net/dosdiosas_/article/details/105704966