归并排序在链表中的应用
Code:
//Runtime: 66 ms
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2){
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *p = l1->val > l2->val ? l2 : l1;
ListNode *prev = NULL;
while (l1 != NULL && l2 != NULL){
if (l1->val <= l2->val){
if (prev != NULL){ prev->next = l1; }
prev = l1;
l1 = l1->next;
}
else{
if (prev != NULL){ prev->next = l2; }
prev = l2;
l2 = l2->next;
}
}
if (l2 == NULL){ prev->next = l1; }
else if (l1 == NULL){ prev->next = l2; }
return p;
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
if (lists.size() == 0) return NULL;
if (lists.size() == 1) return lists[0];
else{
vector<ListNode*> left, right;
int mid = lists.size() >> 1;
for (int i = 0; i < mid; ++i) left.push_back(lists[i]);
for (int i = mid; i < lists.size(); ++i) right.push_back(lists[i]);
ListNode *l1 = mergeKLists(left);
ListNode *l2 = mergeKLists(right);
return mergeTwoLists(l1, l2);
}
}