常数的空间复杂度,用归并排序递归实现
/** * 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) {} * }; struct ListNode { int val; ListNode* next; ListNode(int x):val(x),next(nullptr){} }; */ class Solution { public: ListNode* mergeList(ListNode* l1,ListNode* l2) { if(!l1) return l2;if(!l2) return l1; ListNode dummy(-1),*root=&dummy; while(l1&&l2) { root->next=l1->val<=l2->val?l1:l2; if(l1->val<=l2->val) l1=l1->next; else l2=l2->next; root=root->next; } root->next=l1==nullptr?l2:l1; return dummy.next; } ListNode* sortList(ListNode* head) { //如果没有要直接返回head本身,因为代表不需要排序,而不能是空 if(!head||!head->next) return head; ListNode *fast=head,*slow=head; while(slow->next&&fast->next&&fast->next->next) { slow=slow->next; fast=fast->next->next; } fast=slow->next; slow->next=nullptr; //本身要加sort排序,这是递归 return mergeList(sortList(head),sortList(fast)); } };
愿为天下目,萃聚六路华