-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathleetcode-merge-k-sorted-lists.cpp
62 lines (51 loc) · 1.18 KB
/
leetcode-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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// https://leetcode.com/problems/merge-k-sorted-lists/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Comparator
{
public:
bool operator() (const ListNode *a, const ListNode *b)
{
return a->val>b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty())
return NULL;
priority_queue<ListNode*, std::vector<ListNode*>, Comparator> p;
for(int i=0;i<lists.size();i++)
{
if(lists[i])
{
p.push(lists[i]);
}
}
ListNode *head=NULL,*p1=NULL;
while(!p.empty())
{
ListNode *a=p.top();
p.pop();
if(head==NULL)
{
head=a;
p1=head;
}
else
{
p1->next=a;
p1=p1->next;
}
if(a->next)
p.push(a->next);
}
return head;
}
};