-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp023.cpp
44 lines (42 loc) · 1.01 KB
/
p023.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) {}
* };
*/
struct cmp {
bool operator()(ListNode *a, ListNode *b)
{
return a->val < b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
multiset<ListNode*, cmp> ms;
ListNode *head = new ListNode(0);
ListNode *cur = head;
vector<ListNode*>::iterator iter;
for (iter = lists.begin(); iter != lists.end(); iter++)
{
if (*iter != NULL)
{
ms.insert(*iter);
}
}
while (!ms.empty())
{
ListNode *tmp = *ms.begin();
ms.erase(ms.begin());
cur->next = tmp;
if (tmp->next != NULL)
{
ms.insert(tmp->next);
}
cur = tmp;
}
return head->next;
}
};