Skip to content

Instantly share code, notes, and snippets.

@mmalinin
Created July 28, 2021 21:03
Show Gist options
  • Save mmalinin/0087a5342517c2dbc993ed9176242b3f to your computer and use it in GitHub Desktop.
Save mmalinin/0087a5342517c2dbc993ed9176242b3f to your computer and use it in GitHub Desktop.
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<ListNode*> allNodes;
vector<int> integers;
for(auto& element : lists) {
while(element != nullptr) {
allNodes.push_back(element);
integers.push_back(element->val);
element = element->next;
}
}
sort(integers.begin(), integers.end());
auto size = integers.size();
if (size == 0) {
return nullptr;
}
if (size > 1) {
for (int i = 0; i < size - 1; ++i) {
allNodes[i]->next = allNodes[i+1];
allNodes[i]->val = integers[i];
}
}
allNodes[size-1]->next = nullptr;
allNodes[size-1]->val = integers[size-1];
return allNodes[0];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment