-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge k Sorted Lists.cpp
44 lines (42 loc) · 1.08 KB
/
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
struct cmp {
bool operator() (ListNode *a, ListNode *b) {
return a->val > b->val;
}
};
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
priority_queue<ListNode *, vector<ListNode *>, cmp> queue;
for (int i = 0; i < lists.size(); i++) {
if (lists[i] != NULL) {
queue.push(lists[i]);
}
}
ListNode *head = NULL, *prev = NULL, *temp;
while (!queue.empty()) {
temp = queue.top();
queue.pop();
if (prev == NULL) {
head = temp;
}
else {
prev->next = temp;
}
prev = temp;
if (temp->next != NULL) {
queue.push(temp->next);
}
}
return head;
}
};