1,题目描述
2,题目分析
参考代码:https://blog.csdn.net/yuanliang861/article/details/83755684
3,代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
//通过以下的循环找到链表的中点,将链表分为两个部分
ListNode *slow=head,*fast=head;
while(slow->next!=NULL && fast->next!=NULL && fast->next->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
ListNode *last=slow->next;
slow->next=NULL;
ListNode *pre=sortList(head);
ListNode *las=sortList(last);
return merge(pre,las);
}
ListNode* merge(ListNode *l1 , ListNode *l2)
{
ListNode* dummy=new ListNode(0);
ListNode* p=dummy;
while(l1 && l2)
{
if(l1->val > l2->val)
{
p->next=l2;
p=p->next;
l2=l2->next;
}
else
{
p->next=l1;
p=p->next;
l1=l1->next;
}
}
//最后一定要加这两句
if(NULL==l1) p->next=l2;
if(NULL==l2) p->next=l1;
return dummy->next;
}
};