-
Notifications
You must be signed in to change notification settings - Fork 12
/
MergeKSortedLists.cpp
44 lines (37 loc) · 978 Bytes
/
MergeKSortedLists.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) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size(), i = 0;
priority_queue<int, vector<int>, greater<int> > q;
while(i < n){
ListNode* curr = lists[i];
while(curr){
q.push(curr->val);
curr = curr->next;
}
i++;
}
ListNode* head = NULL, *curr = NULL;
while(!q.empty()){
ListNode* temp = new ListNode(q.top());
if(!head){
head = temp;
curr = temp;
}
else{
curr->next = temp;
curr = temp;
}
q.pop();
}
return head;
}
};