forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_k_Sorted_Lists.cc
42 lines (42 loc) · 1.09 KB
/
Merge_k_Sorted_Lists.cc
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp {
bool operator () (ListNode *x, ListNode *y) {
return x->val > y->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
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;
}
};