✌粤嵌—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;
}
相关推荐
修钩.3 小时前
力扣 Pandas 挑战(5)---数据分组
算法·leetcode·pandas
茴香豆的茴14 小时前
转码刷 LeetCode 笔记[1]:3.无重复字符的最长子串(python)
笔记·算法·leetcode
快去睡觉~4 小时前
力扣46:全排列
算法·leetcode·动态规划
蒋星熠4 小时前
字母异位词分组(每天刷力扣hot100系列)
开发语言·c++·算法·leetcode·职场和发展
刚入坑的新人编程7 小时前
暑期算法训练.11
数据结构·c++·算法·leetcode·链表
zjoy_22338 小时前
[算法]Leetcode3487
java·学习·算法·leetcode
蒟蒻小袁8 小时前
力扣面试150题--只出现一次的数字II
算法·leetcode·面试
YuTaoShao10 小时前
【LeetCode 热题 100】20. 有效的括号
java·linux·数据库·leetcode
Dream it possible!13 小时前
LeetCode 面试经典 150_数组/字符串_买卖股票的最佳时机(7_121_C++_简单)(贪心)
c++·leetcode·面试·贪心算法
茴香豆的茴20 小时前
转码刷 LeetCode 笔记[1]:3.无重复字符的最长子串(python)
leetcode