/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct node {
ListNode *lnp;
node() {
lnp = NULL;
}
node (ListNode *_lnp): lnp(_lnp){}
bool operator < (const node &other) const {
return lnp->val > other.lnp->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<node> pq;
ListNode *head = NULL, *current = NULL;
int n = lists.size();
for (int i = 0; i < n; ++i) {
if (lists[i]) {
pq.push(node(lists[i]));
}
}
while (!pq.empty()) {
ListNode *p = pq.top().lnp;
if (!head) {
head = current = p;
} else {
current->next = p;
current = p;
}
pq.pop();
if (p->next) {
pq.push(node(p->next));
}
}
return head;
}
};
Using STL
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head = NULL, *cur = NULL;
priority_queue<pair<int, ListNode*>, vector<pair<int, ListNode*> >, greater<pair<int, ListNode*> > > pq;
for (int i = 0; i < lists.size(); ++i) {
if (lists[i]) {
pq.push(make_pair(lists[i]->val, lists[i]));
}
}
while (!pq.empty()) {
ListNode *next = pq.top().second;
pq.pop();
if (!head) {
head = cur = next;
} else {
cur->next = next;
cur = next;
}
if (next->next) {
pq.push(make_pair(next->next->val, next->next));
}
}
return head;
}
};