✌粤嵌—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;
}
相关推荐
Ka1Yan26 分钟前
[二叉树] - 代码随想录:二叉树的统一迭代遍历
数据结构·算法·leetcode
X在敲AI代码4 小时前
【无标题】
算法·leetcode·职场和发展
月明长歌5 小时前
【码道初阶】Leetcode136:只出现一次的数字:异或一把梭 vs HashMap 计数(两种解法完整复盘)
java·数据结构·算法·leetcode·哈希算法
Swift社区5 小时前
LeetCode 456 - 132 模式
java·算法·leetcode
LYFlied5 小时前
【每日算法】LeetCode 152. 乘积最大子数组(动态规划)
前端·算法·leetcode·动态规划
圣保罗的大教堂5 小时前
leetcode 3075. 幸福值最大化的选择方案 中等
leetcode
Dream it possible!5 小时前
LeetCode 面试经典 150_回溯_单词搜索(104_79_C++_中等)
c++·leetcode·面试·回溯
2401_841495646 小时前
【LeetCode刷题】杨辉三角
数据结构·python·算法·leetcode·杨辉三角·时间复杂度·空间复杂度
LYFlied6 小时前
【每日算法】LeetCode 62. 不同路径(多维动态规划)
前端·数据结构·算法·leetcode·动态规划
yaoh.wang6 小时前
力扣(LeetCode) 119: 杨辉三角 II - 解法思路
数据结构·python·算法·leetcode·面试·职场和发展·跳槽