Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解题思路:一般而言,合并两个有序链表较为简单,只需要两两逐个比较即可.而本题要求合并K个有序链表,事实上只需要对每个链表的头结点建堆.每次输出最小值.并插入其所在链表的下个结点并维护堆.可以利用STL中的优先队列来完成.
#include<iostream>
#include<vector>
#include<queue>
#include<functional>
using namespace std;
//Definition for singly - linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct ListCompare :public binary_function<ListNode*, ListNode*, bool>{
bool operator()(const ListNode*& x, const ListNode*& y)const{ return x->val < y->val; }
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode*, vector<ListNode*>, ListCompare> Q_queue;
for_each(lists.begin(), lists.end(), [&Q_queue](ListNode* head){if(head!=NULL)Q_queue.push(head);}); //建堆
ListNode* ResultNode = new ListNode(0);
ListNode* TmpNode = ResultNode;
while (!Q_queue.empty()){
ListNode* TopListNode = Q_queue.top();
Q_queue.pop();
TmpNode->next = TopListNode;
TmpNode = TmpNode->next;
if (TopListNode->next != NULL)
Q_queue.push(TopListNode->next);
}
return ResultNode->next;
}