✌粤嵌—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;
}
相关推荐
唐梓航-求职中2 分钟前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode
YGGP11 分钟前
【Golang】LeetCode 1. 两数之和
leetcode
唐梓航-求职中13 分钟前
编程大师-技术-算法-leetcode-355. 设计推特
算法·leetcode·面试
唐梓航-求职中21 分钟前
技术-算法-leetcode-1606. 找到处理最多请求的服务器(易懂版)
服务器·算法·leetcode
YGGP3 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
月挽清风11 小时前
代码随想录第十五天
数据结构·算法·leetcode
TracyCoder12313 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
We་ct14 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
努力学算法的蒟蒻17 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_8414956417 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列