https://leetcode.com/problems/merge-k-sorted-lists/description/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<pair<int,ListNode*>> q; for (auto p : lists) if (p) q.push({-p->val, p}); ListNode h(0); ListNode *cur = &h; while (!q.empty()) { auto p = q.top().second; q.pop(); cur->next = p; cur = p; if (p->next) { q.push( {-p->next->val, p->next} ); } } cur->next = NULL; return h.next; } };