diff --git a/include/s0023_merge_k_sorted_lists.hpp b/include/s0023_merge_k_sorted_lists.hpp new file mode 100644 index 0000000..3ddf1d7 --- /dev/null +++ b/include/s0023_merge_k_sorted_lists.hpp @@ -0,0 +1,21 @@ +#ifndef S0023_MERGE_K_SORTED_LISTS +#define S0023_MERGE_K_SORTED_LISTS + +#include + +using namespace std; + +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); +}; + +#endif diff --git a/src/s0023_merge_k_sorted_lists.cpp b/src/s0023_merge_k_sorted_lists.cpp new file mode 100644 index 0000000..6fa1f4b --- /dev/null +++ b/src/s0023_merge_k_sorted_lists.cpp @@ -0,0 +1,43 @@ +#include "s0023_merge_k_sorted_lists.hpp" + +ListNode *mergeTwoLists(ListNode *a, ListNode *b) { + if (a == nullptr) { + return b; + } else if (b == nullptr) { + return a; + } + ListNode dummy; + ListNode *tail = &dummy; + while (a != nullptr && b != nullptr) { + if (a->val > b->val) { + tail->next = b; + b = b->next; + } else { + tail->next = a; + a = a->next; + } + tail = tail->next; + } + if (a == nullptr) { + tail->next = b; + } else { + tail->next = a; + } + return dummy.next; +} + +// 分治合并 +ListNode *merge(vector &lists, int l, int r) { + if (l == r) { + return lists[l]; + } + if (l > r) { + return nullptr; + } + int mid = (l + r) >> 1; + return mergeTwoLists(merge(lists, 1, mid), merge(lists, mid + 1, r)); +} + +ListNode* Solution::mergeKLists(vector& lists) { + return merge(lists, 0, lists.size() - 1); +}