-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemp.cpp
41 lines (37 loc) · 989 Bytes
/
temp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<queue>
#include<string>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class compare{
public:
bool operator()(ListNode*& a, ListNode*& b){
return a->val > b->val;
}
};
class Solution {
private:
ListNode *head = NULL, *tail = NULL;
void add(ListNode*& head, ListNode*& tail, ListNode* cur){
if (head) tail->next = cur, tail = cur;
else head = tail = cur;
}
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
ListNode *head = NULL, *tail = NULL;
priority_queue<ListNode*, vector<ListNode*>, compare> pq;
for (int i = 0;i < lists.size(); i++) if (lists[i])
pq.push(lists[i]);
while(!pq.empty()){
ListNode* h = pq.top(); pq.pop();
add(head, tail, h);
if (h->next){
pq.push(h->next);
}
}
return head;
}
};