✌粤嵌—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;
}
相关推荐
吃着火锅x唱着歌2 小时前
LeetCode 2016.增量元素之间的最大差值
数据结构·算法·leetcode
元亓亓亓4 小时前
LeetCode热题100--46. 全排列--中等
算法·leetcode·职场和发展
墨染点香5 小时前
LeetCode 刷题【146. LRU 缓存】
leetcode·缓存·哈希算法
qk学算法5 小时前
力扣滑动窗口题目-76最小覆盖子串&&1234替换子串得到平衡字符串
数据结构·算法·leetcode
小欣加油5 小时前
leetcode 860 柠檬水找零
c++·算法·leetcode·职场和发展·贪心算法
还是码字踏实5 小时前
基础数据结构之数组的矩阵遍历:螺旋矩阵(LeetCode 54 中等题)
数据结构·leetcode·矩阵·螺旋矩阵
im_AMBER8 小时前
算法笔记 10
笔记·学习·算法·leetcode
夏鹏今天学习了吗16 小时前
【LeetCode热题100(59/100)】分割回文串
算法·leetcode·深度优先
还是码字踏实16 小时前
基础数据结构之数组的双指针技巧之对撞指针(两端向中间):三数之和(LeetCode 15 中等题)
数据结构·算法·leetcode·双指针·对撞指针
轮到我狗叫了18 小时前
力扣.84柱状图中最大矩形 力扣.134加油站牛客.abb(hard 动态规划+哈希表)牛客.哈夫曼编码
算法·leetcode·职场和发展