题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <functional> #include <utility> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类vector * @return ListNode类 */ ListNode* mergeKLists(vector<ListNode*>& lists) { // write code here priority_queue<pair<int, ListNode*>, vector<pair<int,ListNode*>>, std::greater<>>que; for(auto & list : lists){ if(list!=nullptr){ que.push(make_pair(list->val, list)); } } auto* head = new ListNode(0); ListNode* cur = head; while(!que.empty()){ ListNode* temp = que.top().second; que.pop(); cur->next = temp; cur = cur->next; if(temp->next!=nullptr){ que.push(make_pair(temp->next->val, temp->next)); } } return head->next; } };