✌粤嵌—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;
}
相关推荐
mask哥6 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
流年如夢10 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
星星码️15 小时前
LeetCode刷题简单篇之反转字母
c++·算法·leetcode
sheeta199819 小时前
LeetCode 每日一题笔记 日期:2026.05.10 题目:2770. 达到末尾下标所需的最大跳跃次数
笔记·算法·leetcode
shehuiyuelaiyuehao20 小时前
算法21,搜索插入位置
python·算法·leetcode
_深海凉_20 小时前
LeetCode热题100-回文链表
算法·leetcode·链表
小雅痞20 小时前
[Java][Leetcode middle] 54. 螺旋矩阵
java·leetcode·矩阵
pursuit_csdn20 小时前
力扣周赛 501
算法·leetcode·职场和发展
AbandonForce20 小时前
LeetCode 滑动窗口个人思路详解
算法·leetcode·职场和发展
Liangwei Lin21 小时前
LeetCode 45. 跳跃游戏 II
数据结构·算法·leetcode