对链表进行归并排序,两个链表的合并可以借用 合并两个有序链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == nullptr){
return head;
}
int len = 0;
ListNode* cur = head;
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
while(cur != nullptr){
cur = cur->next;
len++;
}
for(int i = 1; i < len; i <<= 1){
ListNode* prev = dummyhead, * curr = dummyhead->next;
while(curr != nullptr){
ListNode* l1 = curr;
for(int j = 1; j < i && curr->next != nullptr; j++){
curr = curr->next;
}
ListNode* l2 = curr->next;
curr->next = nullptr;
curr = l2;
ListNode* next = nullptr;
for(int j = 1; j < i && curr != nullptr && curr->next != nullptr; j++){
curr = curr->next;
}
if(curr != nullptr){
next = curr->next;
curr->next = nullptr;
}
ListNode* merged = mergeTwoList(l1, l2);
prev->next = merged;
while(prev->next != nullptr){
prev = prev->next;
}
curr = next;
}
}
return dummyhead->next;
}
ListNode* mergeTwoList(ListNode* list1, ListNode* list2){
ListNode* dummyhead = new ListNode(0);
ListNode* pre = dummyhead;
while(list1 != nullptr && list2 != nullptr){
if(list1->val < list2->val){
pre->next = list1;
list1 = list1->next;
}else {
pre->next = list2;
list2 = list2->next;
}
pre = pre->next;
}
list1 == nullptr ? pre->next = list2 : pre->next = list1;
return dummyhead->next;
}
};