forked from daizhenyang/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge k Sorted Lists.cpp
More file actions
48 lines (47 loc) · 1.07 KB
/
Merge k Sorted Lists.cpp
File metadata and controls
48 lines (47 loc) · 1.07 KB
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct cmp
{
bool operator() (ListNode * lhs, ListNode *rhs) const
{
return lhs->val>rhs->val;
}
};
class Solution {
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>pq;
for (int i=0;i<lists.size();i++)
{
if (lists[i]!=NULL)pq.push(lists[i]);//lists[i]!=NULL
}
ListNode *head=NULL,*ptr=NULL;
while (!pq.empty())
{
ListNode *tmp=pq.top();
pq.pop();
if (!head)
{
head=ptr=tmp;
}
else
{
ptr->next=tmp;
ptr=tmp;
}
if (tmp->next)
{
pq.push(tmp->next);
}
}
return head;
}
};