力扣刷题——排序链表
给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3] 输出:[1,2,3,4]
思路:我们可以采用二分加合并两个有序链表的方法,找到链表的中间节点,然后将其分为两个子链表递归的进行合并。因为我们采用了递归,所以在合并两个链表时就会对其进行排序,合并完成后的链表即为有序的。
class Solution {
ListNode *Half(ListNode *head)
{
ListNode *fast=head;
ListNode *slow=head;
ListNode *pre;
while(fast&&fast->next)
{
pre=slow;
fast=fast->next->next;
slow=slow->next;
}
pre->next=nullptr;
return slow;
}
ListNode *merge(ListNode *head1,ListNode *head2)
{
if(!head1) return head2;
if(!head2) return head1;
if(head1->val<head2->val)
{
head1->next=merge(head1->next,head2);
return head1;
}
head2->next=merge(head1,head2->next);
return head2;
}
public:
ListNode* sortList(ListNode* head) {
if(!head||!head->next)
{
return head;
}
ListNode *head2=Half(head);
head=sortList(head);
head2=sortList(head2);
return merge(head,head2);
}
};