diff --git a/solved/LeetCode/Challenges/2020/January/24.cc b/solved/LeetCode/Challenges/2020/January/24.cc new file mode 100644 index 00000000..16a3d683 --- /dev/null +++ b/solved/LeetCode/Challenges/2020/January/24.cc @@ -0,0 +1,42 @@ +#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) { + set> bestList; + for (auto it : lists) { + if (it != nullptr) { + bestList.insert(make_pair(it->val, it)); + } + } + + ListNode* head = nullptr; + ListNode* cur = nullptr; + while (bestList.size() > 0) { + ListNode* first = bestList.begin()->second; + ListNode* next = first->next; + bestList.erase(bestList.begin()); + if (head == nullptr) { + head = first; + cur = first; + } else { + cur->next = first; + cur = first; + } + if (next != nullptr) { + bestList.insert(make_pair(next->val, next)); + } + } + return head; + } +};