LeetCode - Merge k Sorted Lists
Posted 朽木の半夏
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct compare {
bool operator()(const ListNode* l, const ListNode* r) {
return l->val > r->val;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) { //priority_queue
priority_queue<ListNode *, vector<ListNode *>, compare> key;
for(int i = 0 ; i < lists.size() ; i ++){
if(lists[i])
key.push(lists[i]);
}
ListNode *head = new ListNode(0);
ListNode *p = head;
while(!(key.empty())){
ListNode *fc = key.top();
if(fc->next)
key.push(fc->next);
p->next = fc;
p = fc;
key.pop();
}
return head->next;
}
};
以上是关于LeetCode - Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章
Merge K Sorted Lists -- LeetCode
Leetcode 23: Merge k Sorted Lists
Microsoft leetcode(Merge K Sorted Lists)