struct Node | |
{ | |
ListNode* l; | |
bool operator < (const Node& n) const { | |
return l->val > n.l->val; | |
} | |
// 这里有两种写法 | |
// friend bool operator < ( Node a, Node b) { | |
// return a.l->val > b.l->val; | |
// } | |
}; | |
class Solution { | |
public: | |
ListNode* mergeKLists(vector<ListNode*>& lists) { | |
priority_queue<Node> q; | |
for (ListNode* p : lists) { | |
if(p){ | |
q.push({ p }); | |
} | |
} | |
ListNode head, * tail = &head; | |
while (!q.empty()) { | |
auto temp = q.top(); | |
q.pop(); | |
if (temp.l->next) { | |
q.push({ temp.l->next }); | |
} | |
tail->next = temp.l; | |
tail = tail->next; | |
tail->next = nullptr; | |
} | |
return head.next; | |
} | |
}; |