File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
19 - Heap Data Structure Problems/13 - Merge K Sorted Lists Expand file tree Collapse file tree 1 file changed +48
-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+ class Solution {
19+ public:
20+ ListNode* mergeKLists (vector<ListNode*>& lists) {
21+ priority_queue<ListNode*, vector<ListNode*>, compare> pq;
22+
23+ int k = lists.size ();
24+
25+ if (k == 0 ) return NULL ;
26+ for (int i = 0 ; i < k; i++) if (lists[i] != NULL ) pq.push (lists[i]);
27+
28+ ListNode* head = NULL ;
29+ ListNode* tail = NULL ;
30+
31+ while (pq.size () > 0 ){
32+ ListNode* top = pq.top ();
33+ pq.pop ();
34+
35+ if (head == NULL ){
36+ head = top;
37+ tail = top;
38+ }else {
39+ tail -> next = top;
40+ tail = top;
41+ }
42+
43+ if (top -> next != NULL ) pq.push (top -> next);
44+ }
45+
46+ return head;
47+ }
48+ };
You can’t perform that action at this time.
0 commit comments