/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int n=lists.size();
if (n==0) return NULL;
ListNode *res = new ListNode(0);
ListNode *cur = res;
while (1) {
ListNode *min = NULL;
int index = -1;
for (int i=0; i<n; i++) {
if (lists[i] && (min==NULL || lists[i]->val < min->val)) {
min = lists[i];
index = i;
}
}
if (min == NULL) break;
cur->next = min;
cur = cur->next;
lists[index] = lists[index]->next;
}
return res->next;
}
};
Merge k Sorted Lists
最新推荐文章于 2024-04-03 21:24:25 发布