Following is the c++ code to Merge k Sorted Lists. But i was confused reading the first 4 lines of code. I know what it does just confused how it does it. Could anybody explain these lines to me?
Why use struct? What are the "()" for after "operator"? Why use ">" rather than "<" since all the lists including the result list are in ascending order?
struct compare {
bool operator() (ListNode* &left, ListNode* &right) {
return left->val > right->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode *, vector<ListNode *>, compare> heap;
for (int i = 0; i < lists.size(); i++) {
if (lists[i]) heap.push(lists[i]);
}
ListNode *dummy = new ListNode(0);
ListNode *cur = dummy;
while (!heap.empty()) {
ListNode *min = heap.top();
heap.pop();
cur->next = min;
cur = min;
if (min->next) {
heap.push(min->next);
}
}
return dummy->next;
}
};