not a java person, was here to view tricks to write clean c++ code, no c++ solution provided
No c++ soln provided
Node *mergeKLists(Node *list[], int k)
{
// create an empty min-heap
priority_queue<Node*, std::vector<Node*>, comp> pq;
// push first node of each list into the min-heap
for (int i = 0; i < k; i++)
{
pq.push(list[i]);
}
// take two pointers head and tail where head points to the first node
// of the output list and tail points to its last node
Node *head = nullptr, *last = nullptr;
// run till min-heap is empty
while (!pq.empty())
{
// extract minimum node from the min-heap
Node *min = pq.top();
pq.pop();
// add the minimum node to the output list
if (head == nullptr)
{
head = last = min;
}
else
{
last->next = min;
last = min;
}
// take next node from "same" list and insert it into the min-heap
if (min->next != nullptr)
{
pq.push(min->next);
}
}
// return head node of the merged list
return head;
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.