Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
My Submitted Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
struct PNode{
int index;
ListNode* node;
PNode(int id=0,ListNode* n=NULL):index(id),node(n){};
bool operator <(const PNode& ob)const {return node->val > ob.node->val;};
};
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<PNode> pq; //优先级队列 也可以用堆
int size=lists.size();
ListNode* newhead=NULL;
ListNode* tail=NULL;
for(int i=0;i<size;i++){
if(lists[i]!=NULL){
pq.push(PNode(i,lists[i]));
lists[i]=lists[i]->next;
}
}
while(!pq.empty()){
ListNode* pt=pq.top().node;
if(newhead==NULL){
newhead=pt;
tail=pt;
}
else{
tail->next=pt;
tail=pt;
}
int id=pq.top().index;
pq.pop();
if(lists[id]!=NULL){
pq.push(PNode(id,lists[id]));
lists[id]=lists[id]->next;
}
}
if(tail)
tail->next=NULL;
return newhead;
}
};