Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
学习并练习 priority_queue.
priority_queue的几个重要函数 push pop top.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp
{
bool operator()(ListNode * a,ListNode *b)
{
return a->val > b->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue <ListNode* , vector<ListNode*> ,cmp> qu;
if(lists.size()==0)return NULL;
for(int i = 0 ; i < lists.size() ; i++)if(lists[i] != NULL)qu.push(lists[i]);
ListNode * head = new ListNode(0), *temp = head;
head ->next = NULL;
while(!qu.empty())
{
temp -> next = qu.top();
qu.pop();
temp = temp->next;
ListNode * tmp = temp->next;
if(tmp != NULL)qu.push(tmp);
}
return head->next;
}
};
posted on 2014-03-10 15:42 pengyu2003 阅读(120) 评论(0) 收藏 举报
浙公网安备 33010602011771号