✌粤嵌—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;
}
相关推荐
文丑颜不良啊10 小时前
LeetCode1481~1500题目解析
java·leetcode
文丑颜不良啊11 小时前
LeetCode1381~1400题目解析
java·leetcode
Tisfy14 小时前
LeetCode 3882.网格图中最小异或路径:动态规划
算法·leetcode·动态规划
A boy CDEF girl15 小时前
算法题专栏:优选算法
数据结构·算法·leetcode
驭渊的小故事21 小时前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
文丑颜不良啊1 天前
LeetCode1501~1520题目解析
java·leetcode
Navigator_Z1 天前
LeetCode //C - 1311. Get Watched Videos by Your Friends
c语言·算法·leetcode
Pniubi1 天前
力扣42接雨水(动态规划法)
算法·leetcode·职场和发展
Pniubi1 天前
力扣46全排列(回溯(递归))
算法·leetcode·职场和发展
文丑颜不良啊1 天前
LeetCode1461~1480题目解析
java·leetcode