✌粤嵌—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;
}
相关推荐
kcwqxx1 小时前
day37|完全背包基础+leetcode 518.零钱兑换II ,377.组合总和II
c++·算法·leetcode·动态规划
sjsjs113 小时前
【数据结构-字典树】力扣14. 最长公共前缀
数据结构·leetcode
JNU freshman4 小时前
力扣第435场周赛讲解
算法·leetcode·蓝桥杯
pursuit_csdn7 小时前
力扣 347. 前 K 个高频元素
算法·leetcode
makabaka_T_T7 小时前
25寒假算法刷题 | Day1 | LeetCode 240. 搜索二维矩阵 II,148. 排序链表
数据结构·c++·算法·leetcode·链表·矩阵
余辉zmh10 小时前
【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(二)
c++·算法·leetcode·贪心算法
余辉zmh11 小时前
【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(一)
c++·算法·leetcode·贪心算法
taoyong00111 小时前
代码随想录算法训练营第三十七天-动态规划-完全背包-377. 组合总和 Ⅳ
c++·算法·leetcode·动态规划
因兹菜13 小时前
[LeetCode]day4 977.有序数组的平方
数据结构·算法·leetcode
Joyner20181 天前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展