-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathsolution.cpp
47 lines (41 loc) · 1.03 KB
/
solution.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 Compare
{
bool operator()(const ListNode*p, const ListNode* q)const{
return p->val > q->val;
}
};
class Solution
{
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
int length = lists.size();
ListNode *head = new ListNode(0);
ListNode *pointer = head;
priority_queue<ListNode*, vector<ListNode*>, Compare> listQueue;
for (int i=0; i<length; i++)
{
if (lists[i])
listQueue.push(lists[i]);
}
while (listQueue.size() > 0)
{
ListNode* tempNode = listQueue.top();
listQueue.pop();
pointer->next = tempNode;
pointer = pointer->next;
if (tempNode->next)
listQueue.push(tempNode->next);
}
pointer->next = NULL;
return head->next;
}
};