Skip to content

Commit b74c791

Browse files
Merge pull request pranjay-poddar#184 from JayantGoel001/master
Create MergeKSortedList.cpp
2 parents 837b71a + 5004434 commit b74c791

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

CONTRIBUTERS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,4 @@
6868
* @Chayan-11
6969
* @riya1916
7070
* @Samriddh2703
71+
* @JayantGoel001
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
3+
Merge all the linked-lists into one sorted linked-list and return it.
4+
*/
5+
6+
7+
#include <bits/stdc++.h>
8+
#define pil pair<int,ListNode *>
9+
using namespace std;
10+
// Defining a struct of ListNode
11+
struct ListNode {
12+
int val;
13+
ListNode *next;
14+
ListNode() : val(0), next(nullptr) {}
15+
ListNode(int x) : val(x), next(nullptr) {}
16+
ListNode(int x, ListNode *next) : val(x), next(next) {}
17+
};
18+
ListNode* mergeKLists(vector<ListNode*>& lists) {
19+
//creating a priority queue with elements in increasing order.
20+
priority_queue<pil,vector<pil>,greater<pil>> pq;
21+
22+
//Inserting a pair of integer and ListNode head.
23+
for(auto it : lists){
24+
if(it){
25+
pq.push({it->val,it});
26+
}
27+
}
28+
//Creating A New head pointer to store merged Lists.
29+
ListNode *temp = new ListNode();
30+
ListNode *head = temp;
31+
32+
//Iterating till priority queue gets empty.
33+
while(!pq.empty()){
34+
35+
// Popping the smallest element.
36+
pil top = pq.top();
37+
pq.pop();
38+
39+
// Pointing head pointer to smallest element pointer.
40+
temp->next = top.second;
41+
42+
//Checking if next element exists on current list or not.
43+
if(top.second->next){
44+
pq.push({top.second->next->val,top.second->next});
45+
}
46+
temp = temp->next;
47+
}
48+
return head->next;
49+
}
50+
/*
51+
Input :
52+
[
53+
1->4->5,
54+
1->3->4,
55+
2->6
56+
]
57+
Output :
58+
1->1->2->3->4->4->5->6
59+
*/

0 commit comments

Comments
 (0)