-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMergeKSortedLists.cpp
More file actions
63 lines (57 loc) · 1.4 KB
/
Copy pathMergeKSortedLists.cpp
File metadata and controls
63 lines (57 loc) · 1.4 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Leetcode
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class MyCompare {
public:
bool operator()(ListNode *a, ListNode *b) {
return (a->val) > (b->val);
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*,vector<ListNode*>,MyCompare> q;
int n=lists.size();
if(n==0)
return NULL;
for(int i=0;i<n;i++)
{
struct ListNode *temp=lists[i];
while(temp!=NULL)
{
q.push(temp);
temp=temp->next;
}
}
ListNode *head=NULL,*prev=NULL;
while(!q.empty())
{
ListNode *temp=q.top();
q.pop();
if(head==NULL)
{
head=temp;
prev=temp;
}
else
{
prev->next=temp;
prev=temp;
}
}
if(head!=NULL)
prev->next=NULL;
return head;
}
};