23. 合并K个升序链表

给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。

输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector& lists) {
        return merge(lists, 0, lists.size()-1);
    }

    ListNode* merge(vector& a, int left, int right) {
        if (left == right) return a[left];
        if (left > right) return nullptr;
        int mid = (right+left)>>1;
        return mergeTwoLists(merge(a, left, mid), merge(a, mid+1, right));
    }

    ListNode* mergeTwoLists(ListNode* a, ListNode* b) {
        if (a == nullptr) return b;
        if (b == nullptr) return a;
        ListNode* head = new ListNode;
        ListNode* dummy = head;
        while (a && b) {
            if (a->val < b->val) {
                dummy->next = a;
                a = a->next;
            } else {
                dummy->next = b;
                b = b->next;
            }
            dummy = dummy->next;
        }
        dummy->next = a != nullptr ? a : b;
        return head->next;
    }
};

你可能感兴趣的:(23. 合并K个升序链表)