LeetCode 23. Merge k Sorted Lists
Posted Draymonder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 23. Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。
题目链接
n是总共的数.. k为k个链表
并且学习了优先队列的比较器如何写......
/**
* 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> que;
for(int i=0; i<lists.size(); i++) {
if(lists[i])
que.push(lists[i]);
}
ListNode *first = new ListNode(-0x3f3f3f3f);
ListNode *cur = first;
while(!que.empty()) {
ListNode *top = que.top();
que.pop();
if(top) {
first->next = top;
first = first->next;
if(first && first->next) {
que.push(first->next);
}
}
}
// first->next = NULL;
return cur->next;
}
};
以上是关于LeetCode 23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 23. Merge k Sorted Lists
[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表
[LeetCode]23. Merge k Sorted Lists
leetcode23. Merge k Sorted Lists