链接:https://leetcode.com/problems/merge-k-sorted-lists/description/
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: struct cmp{ bool operator()(const ListNode* a,const ListNode* b) { return a->val>b->val; } }; ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<ListNode*,vector<ListNode*>,cmp> pq; for(auto l: lists) { if(l) { pq.push(l); } } if(pq.empty()) { return nullptr; } ListNode* ans=pq.top(); pq.pop(); ListNode* tail=ans; if(tail->next) { pq.push(tail->next); } while(!pq.empty()) { tail->next=pq.top(); tail=tail->next; pq.pop(); if(tail->next) { pq.push(tail->next); } } return ans; } };