leetcode 148. Sort List
https://leetcode.com/problems/sort-list/discuss/46714/Java-merge-sort-solution
链表初始化代码:ListNode* origin = new ListNode (0);
此题要求时间复杂度是o(nlogn),空间复杂度是o(1),快排最高时间复杂度可能到达o(n2),所以用归并排序,数组的归并排序,还需要o(n)的空间复杂度,但链表不用
归并排序是先划分再融合
https://www.cnblogs.com/chengxiao/p/6194356.html图解归并排序
注意的点:因为要拆分成两个链表,所以一定要从中间那个值一定要加null
class Solution { public: ListNode* sortList(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* slow = head; ListNode* fast = head; while(fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; } ListNode* newhead = slow->next; slow->next = NULL; ListNode* p1 = sortList(head); ListNode* p2 = sortList(newhead); return merge(p1,p2); } ListNode* merge(ListNode* p1,ListNode* p2){ ListNode* dummy = new ListNode(-1); ListNode* p = dummy; while(p1 != NULL && p2 != NULL){ if(p1->val < p2->val){ p->next = p1; p1 = p1->next; p = p->next; } else{ p->next = p2; p2 = p2->next; p = p->next; } } if(p1) p->next = p1; else p->next = p2; return dummy->next; } };