forked from VinayBelwal/Hactober-22-Programs-and-Projects-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge_sorted_list.cpp
35 lines (35 loc) · 860 Bytes
/
Merge_sorted_list.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
class mycomp{
public:
bool operator()(ListNode* a,ListNode * b){
return (a->val)>(b->val);
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n=lists.size();
if(n==0)
return nullptr;
priority_queue<ListNode* ,vector<ListNode*>,mycomp>q;
for(int i=0;i<n;i++){
if(lists[i]!=nullptr)
q.push(lists[i]);
}
if(q.empty())
return nullptr;
ListNode * head=q.top();
if(head->next!=nullptr)
q.push(head->next);
q.pop();
ListNode * temp=head;
while(!q.empty()){
auto u=q.top();
q.pop();
if(u->next!=nullptr)
q.push(u->next);
temp->next=u;
temp=u;
}
return head;
}
};