✌粤嵌—2024/4/3—合并K个升序链表✌

代码实现:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* merge(struct ListNode *l1, struct ListNode *l2) {
    if (l1 == NULL) {
        return l2;
    }
    if (l2 == NULL) {
        return l1;
    }
    struct ListNode *head = malloc(sizeof(*head)); // 设置虚拟头结点
    struct ListNode *tail = head;
    while (l1 && l2) {
        if (l1->val < l2->val) {
            tail->next = l1;
            l1 = l1->next;
        } else {
            tail->next = l2;
            l2 = l2->next;
        }
        tail = tail->next;
        tail->next = NULL;
    }
    if (l1) {
        tail->next = l1;
    }
    if (l2) {
        tail->next = l2;
    }
    struct ListNode *result = head->next;
    head->next = NULL;
    free(head);
    return result;   
}

struct ListNode* mergeKLists(struct ListNode **lists, int listsSize){
    if (lists == NULL || listsSize == 0) {
        return NULL;
    }
    struct ListNode *h = NULL;
    for (int i = 0; i < listsSize; i++) {
        h = merge(lists[i], h);
    }
    return h;
}
相关推荐
8Qi84 小时前
LeetCode 235. 二叉搜索树的最近公共祖先(LCA)
算法·leetcode·二叉树·递归·二叉搜索树·lca·迭代
8Qi86 小时前
LeetCode 494:目标和(Target Sum)—— 题解 ✅
算法·leetcode·职场和发展·动态规划·01背包
这料鬼有毒8 小时前
二刷hot100-78.子集
算法·leetcode·职场和发展
医用门11 小时前
医院钢制门厂家有哪些品牌好的
leetcode
mifengxing11 小时前
LeetCode热题100——字母异位词分组
java·算法·leetcode·职场和发展·哈希表·hot100
小欣加油13 小时前
leetcode41 缺失的第一个正数
数据结构·c++·算法·leetcode
木井巳14 小时前
【DFS解决floodfill算法】岛屿数量
java·算法·leetcode·深度优先
凯瑟琳.奥古斯特15 小时前
力扣1003题C++解法详解
开发语言·c++·算法·leetcode·职场和发展
剑挑星河月15 小时前
98.验证二叉搜索树
java·算法·leetcode
罗超驿15 小时前
16.滑动窗口经典例题:最小覆盖子串(LeetCode 76)算法原理剖析
算法·leetcode·职场和发展