148. 排序链表
归并排序
/**
* 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* merge(ListNode* h1, ListNode* h2) {
if (!h1) return h2;
if (!h2) return h1;
ListNode* dummy = new ListNode();
ListNode* cur = dummy;
while (h1 && h2) {
if (h1->val < h2->val) {
cur->next = h1;
h1 = h1->next;
} else {
cur->next = h2;
h2 = h2->next;
}
cur = cur->next;
}
cur->next = h1 ? h1 : h2;
return dummy->next;
}
ListNode* sortList(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
// 通过快慢指针将链表分割为两部分
ListNode* left = head;
ListNode* mid = head->next;
ListNode* right = head->next->next;
while (right && right->next) {
right = right->next->next;
left = left->next;
mid = mid->next;
}
left->next = nullptr;
return merge(sortList(head), sortList(mid));
}
};
23. 合并K个升序链表
归并
// 归并
class Solution {
public:
ListNode* merge(ListNode* head1, ListNode* head2) {
if (head1 == nullptr) return head2;
if (head2 == nullptr) return head1;
ListNode head, *cur = &head, *l1 = head1, *l2 = head2;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1 ->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (!l1) cur->next = l2;
if (!l2) cur->next = l1;
return head.next;
}
ListNode* mergeK(vector<ListNode*>& lists, int l, int r) {
if (l > r) return nullptr;
if (l == r) return lists[l];
int mid = (l + r) >> 1;
return merge(mergeK(lists, l, mid), mergeK(lists, mid + 1, r));
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return nullptr;
return mergeK(lists, 0, lists.size() - 1);
}
};