-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.Merge k Sorted Lists.cpp
46 lines (40 loc) · 1.04 KB
/
23.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp {
bool operator()(ListNode *a, ListNode *b) {
if(a->val < b->val)
return 0;
return 1;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
std::priority_queue<ListNode*, std::vector<ListNode*>, cmp> que;
for (int i = 0; i < lists.size(); ++i) {
if (lists[i] != NULL)
que.push(lists[i]);
}
ListNode *head = new ListNode(0);
ListNode *ptr = head;
while (!que.empty()) {
ListNode *tmp = que.top();
que.pop();
ptr->next = new ListNode(tmp->val);
ptr = ptr->next;
if (tmp->next != NULL) {
que.push(tmp->next);
}
}
ptr = head;
head = head->next;
delete ptr;
return head;
}
};