使用优先级队列
struct cmp{
bool operator() ( ListNode* a, ListNode* b ){
return a->val>b->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
// Note: The Solution object is instaentiated only once and is reused by each test case.
int k = lists.size();
priority_queue<ListNode*,vector<ListNode*>,cmp> q;
for(int i=0;i<k;i++)
{
if(lists[i]) //attention, judege if it's NULL
q.push(lists[i]);
}
ListNode* newHead = NULL;
ListNode* tail;
while(!q.empty())
{
ListNode* n = q.top();
q.pop();
if(!newHead)
tail = newHead = n;
else
{
tail->next = n;
tail = n;
}
if(n->next)
q.push(n->next);
}
return newHead;
}
};