将K个已排序的链表合并为一个有序的链表
输入:K个有序List
输出:一个有序List
代码:
/*
Ethan
mergeKSortedLists
2016.3.1
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x),next(NULL){}
};
class Solution {
struct cmp{
bool operator() (ListNode *x, ListNode *y){
return x->val > y->val;
}
};
public:
ListNode *mergeKLists(vector<ListNode*> &lists){
ListNode *ret = NULL;
ListNode **pCur = &ret;
ListNode *tmp = NULL;
if(lists.size()==0){
return ret;
}
priority_queue<ListNode*,vector<ListNode*>,cmp> que;
for(int i=0;i<lists.size();i++){
if(lists[i]!=NULL){
que.push(lists[i]);
}
}
while(!que.empty()){
tmp = que.top();
que.pop();
*pCur = tmp;
pCur = &((*pCur)->next);
if(tmp->next!=NULL){
que.push(tmp->next);
}
}
return ret;
}
void printList(ListNode *&a){
while(a!=NULL){
cout<<a->val<<"\t";
a = a->next;
}
cout<<endl;
}
};
int main(int argc, char *argv[]) {
vector<ListNode*> lists;
for(int j=1;j<6;j++){
ListNode *list =new ListNode(0);
list->next = NULL;
ListNode *tmp;
tmp = list;
for(int i=1;i<6;i++){
ListNode *p = new ListNode(i*j);
tmp->next = p;
tmp = p;
}
tmp->next = NULL;
lists.push_back(list);
}
Solution a;
ListNode *l = a.mergeKLists(lists);
a.printList(l);
return 0;
}