✌粤嵌—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;
}
相关推荐
郝学胜-神的一滴13 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger13 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Navigator_Z16 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
Pniubi2 天前
力扣2 . 两数相加
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode3421~3440题目解析
java·leetcode
LK_073 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi3 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
文丑颜不良啊3 天前
LeetCode3341~3360题目解析
java·leetcode
Rain的Java大神之路4 天前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode