File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode() : val(0), next(nullptr) {}
7
+ * ListNode(int x) : val(x), next(nullptr) {}
8
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
9
+ * };
10
+ */
11
+
12
+ class compare {
13
+ public:
14
+ bool operator ()(ListNode* a,ListNode* b){
15
+ return a->val >b->val ;
16
+ }
17
+ };
18
+
19
+ class Solution {
20
+ public:
21
+ ListNode* mergeKLists (vector<ListNode*>& lists) {
22
+
23
+ priority_queue<ListNode*,vector<ListNode*>,compare> pq;
24
+
25
+ for (int i=0 ;i<lists.size ();i++){
26
+ if (lists[i]!=NULL ){
27
+ pq.push (lists[i]);
28
+ }
29
+ }
30
+
31
+ if (pq.empty ()){
32
+ return NULL ;
33
+ }
34
+
35
+ ListNode* dummy=new ListNode;
36
+ ListNode* last=dummy;
37
+
38
+ while (!pq.empty ()){
39
+ ListNode* curr=pq.top ();
40
+ pq.pop ();
41
+
42
+ last->next =curr;
43
+ last=last->next ;
44
+
45
+ if (curr->next !=NULL ){
46
+ pq.push (curr->next );
47
+ }
48
+ }
49
+ return dummy->next ;
50
+ }
51
+ };
You can’t perform that action at this time.
0 commit comments