-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMerge k Sorted Lists.cpp
52 lines (43 loc) · 977 Bytes
/
Merge k Sorted Lists.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
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
struct comparator{
bool operator()(ListNode* left, ListNode* right){
return left->val > right->val;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode*,vector<ListNode*>, comparator> q;
for(int i=0;i<lists.size();i++){
if(lists[i]==NULL)
continue;
q.push(lists[i]);
}
ListNode* root=NULL, *tail, *node;
if(q.empty()) return root;
node = q.top();
q.pop();
root = node;
tail = node;
if(node->next) q.push(node->next);
while(!q.empty()){
node = q.top(); q.pop();
tail->next = node;
tail = tail->next;
if(node->next)
q.push(node->next);
}
return root;
}
};
int main(){
cout << "hello\n";
}