-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.cpp
More file actions
39 lines (34 loc) · 933 Bytes
/
MergeKSortedLists.cpp
File metadata and controls
39 lines (34 loc) · 933 Bytes
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
/**
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct Comparator {
bool operator()(TreeNode* left, TreeNode* 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])
q.push(lists[i]);
ListNode dummy(0), *cur = &dummy;
while (!q.empty()) {
ListNode *node = q.top();
q.pop();
cur = cur->next = node;
if (node->next)
q.push(node->next);
}
return dummy.next;
}
};