1 归并排序-自顶向下
递归到只剩一个结点或者为空链表,返回的时候返回合并后的链表头结点。 时间复杂度 O(nlogn) 空间复杂度 O(logn)。首先需要找到中间点将两个链表一分为二,再分两部分进行递归排序,最后使用合并两个有序链表的方法合并两部分。一分为二时使用快慢指针找到中点区分。
// 归并排序
ListNode*merge(ListNode*head1,ListNode*head2){
ListNode*dummy=new ListNode();
ListNode*pre=dummy;
while(head1!=nullptr&&head2!=nullptr){
if(head1->val<=head2->val){
pre->next=head1;
head1=head1->next;
}else{
pre->next=head2;
head2=head2->next;
}
pre=pre->next;
}
pre->next=head1!=nullptr?head1:head2;
return dummy->next;
}
ListNode*findMid1(ListNode*head){
if(head==nullptr||head->next==nullptr){
return head;
}
ListNode*slow=head;
ListNode*fast=head->next;
while(fast&&fast->next){
// fast is 下一个slow
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
ListNode*findMid2(ListNode*head){
if(head==nullptr||head->next==nu