题目
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
思路
1.使用快慢指针把链表分成两半,要断链,同时断了之后还要有两个链表的头节点,所以用快慢指针断链的时候需要一个结点pre记录slow的前驱结点,然后 pre->next==nullptr,那么两个链表即为[head,pre]和[slow,nullptr]。
2.合并链表的方法就是合并排序链表的递归方法。
解题代码
class Solution {
public:
ListNode* sortList(ListNode* head)
{
if(head==nullptr || head->next==nullptr)
return head;
ListNode* slow=head;
ListNode* fast=head;
ListNode* pre=head;
while(fast!=nullptr && fast->next!=nullptr)
{
pre=slow;
slow=slow->next;
fast=fast->next->next;
}
pre->next=nullptr;
return merge(sortList(head),sortList(slow));
}
ListNode* merge(ListNode* l1,ListNode* l2)
{
if(l1==nullptr)
return l2;
if(l2==nullptr)
return l1;
if(l1->val<=l2->val)
{
l1->next=merge(l1->next,l2);
return l1;
}
else
{
l2->next=merge(l1,l2->next);
return l2;
}
}
};