链表排序,归并排序。
/**
* 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* merge(ListNode* l1, ListNode* l2){
ListNode head;
ListNode* trans = &head;
while(l1 && l2){
if(l1->val <= l2->val){
trans ->next = l1;
l1 = l1 ->next;
}else{
trans ->next = l2;
l2 = l2 ->next;
}
trans = trans ->next;
}
if(l1) trans ->next = l1;
if(l2) trans ->next = l2;
return head.next;
}
ListNode* sortList(ListNode* head) {
if(head == nullptr || head ->next == nullptr) return head;
ListNode* slow =head, *fast = head ->next;
while(fast != nullptr && fast ->next != nullptr){
slow = slow ->next;
fast = fast ->next ->next;
}
fast = slow ->next;
slow ->next = nullptr;
// cout << head ->val <<" "<<fast ->val <<endl;
return merge(sortList(head), sortList(fast));
}
};