File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed
Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 6868* @Chayan-11
6969* @riya1916
7070* @Samriddh2703
71+ * @JayantGoel001
Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments