2个有序
http://www.cnblogs.com/grandyang/p/4086297.html
k个有序
https://www.cnblogs.com/grandyang/p/4606710.html
题目:
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
思路:
建一个大小为K的小顶堆(优先队列默认大顶堆,需要自定义降序,变成小顶堆),
先把K个链表的头结点扔进堆,取了堆顶元素后,接着把堆顶元素所在链表的非空结点扔进堆。
#include <iostream>
#include<vector>
#include<queue>
#include<functional>
using namespace std;
typedef struct Node
{
int val;
struct Node* next;
}node;
struct cmp
{
bool operator() (node* a,node* b)
{
return a->val > b->val;
}
};
node* mergek(vector<node*>& lists)
{
priority_queue<node*,vector<node*>,cmp> hp;
for(int i=0;i<lists.size();i++) hp.push(lists[i]);
node* head=NULL;
node* p=NULL;
node* q=NULL;
while(!hp.empty())
{
p=hp.top();
hp.pop();
if(p->next!=NULL) hp.push(p->next);
if(head==NULL)
{
head=p;
q=p;
}
else
{
q->next=p;
q=q->next;
}
}
return head;
}
int main()
{
node* n1=new node;
node* n2=new node;
node* n3=new node;
node* n4=new node;
node* n5=new node;
n1->val=1;
n2->val=2;
n3->val=3;
n4->val=4;
n5->val=5;
n1->next=n2;
n2->next=NULL;
n3->next=NULL;
n4->next=n5;
n5->next=NULL;
vector<node*> v;
v.push_back(n1);
v.push_back(n3);
v.push_back(n4);
node* h=mergek(v);
node* lp=h;
while(lp!=NULL)
{
cout<<lp->val<<" ";
lp=lp->next;
}
}
//output: 1 2 3 4 5