解法1:
二分法,二分插入排序,超时了,算法的时间复杂度应该是O(n^2)
/**
* 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:
void mySortList(ListNode* head, ListNode* tail) {
if(head == tail || head->next == tail) return ;
ListNode *mid = head->next, *p = head->next, *q;
while(p->next != tail) {
q = p->next; // 准备处理的节点
if(q->val < mid->val) {
p->next = q->next; // 记录下一个 p
q->next = head->next;
head->next = q;
}
else p = p->next;
}
mySortList(head, mid);
mySortList(mid, tail);
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* newHead = new ListNode();
newHead->next = head;
mySortList(newHead, nullptr);
return newHead->next;
}
};